package com.lyn.utils_library;
/**
* 16进制和byte[]转换工具类
*
* @author longyn
* @version 1.0.0
*/
public class HexUtil {
/**
* byte[] 数组转16进制字符串
*
* @param src byte[] 数组
* @return hex字符串
*/
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (byte b : src) {
int v = b & 0xFF;
String hv = Integer.toHexString(v).toUpperCase();
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv).append(" ");
}
return stringBuilder.toString();
}
/**
* hex转byte
*
* @param hex 16进制字符
* @return byte
*/
public static byte hexToByte(String hex) {
return (byte) Integer.parseInt(hex, 16);
}
/**
* 16进制字符串转byte[]
*
* @param hex 16进制字符串
* @return byte[] 数据
*/
public static byte[] hexToByteArray(String hex) {
int hexlen = hex.length();
byte[] result;
if (hexlen % 2 == 1) {
//奇数
hexlen++;
result = new byte[(hexlen / 2)];
hex = "0" + hex;
} else {
//偶数
result = new byte[(hexlen / 2)];
}
int j = 0;
for (int i = 0; i < hexlen; i += 2) {
result[j] = hexToByte(hex.substring(i, i + 2));
j++;
}
return result;
}
}
更多推荐
16进制和byte[]转换工具类
发布评论