首先,byte数组转成16进制字符串:
/**
* byte数组转成字符串
*
* @param bytes 数组
* @param isCaptial 使用大写还是小写表示
* @return 转换后的字符串
*/
public static String bytesToHexStr(byte[] bytes, boolean isCaptial) {
if (null == bytes || bytes.length <= 0) {
return null;
}
StringBuilder s = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
if (isCaptial) {
//02表示使用2位16进制字符表示当前的byte数据,X或者x表示16进制字符串
s.append(String.format("%02X", bytes[i]));
} else {
s.append(String.format("%02x", bytes[i]));
}
}
return s.toString();
}
然后,将16进制字符串转成byte数组:
public static byte[] hexStrToBytes(String hex) {
if (null == hex || hex.equals("")) {
return null;
}
int strLength = hex.length();//获取16进制字符串长度
int length = strLength / 2; //获取字节长度
char[] hexChars;//用来存放字符串转换成的字符数组
if (length * 2 < strLength) { // strLength is odd, add '0'
length += 1;
hexChars = ("0" + hex).toCharArray();
} else {
hexChars = hex.toCharArray();
}
byte[] bytes = new byte[length];//用来存放最终组成的数组
for (int i = 0; i < length; i++) {
int pos = i * 2;
//组成1字节的数据。因为是需要两个字符组成一个字节的数据,这就需要第一个字符向左移4位。
bytes[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return bytes;
}
public static byte charToByte(char c) {
byte result = (byte) "0123456789abcdef".indexOf(c);
if (result == -1) {
return (byte) "0123456789ABCDEF".indexOf(c);
} else {
return result;
}
}