二进制数据转化为16进制字符串(中间加的‘:'还有‘;'是为了查看下标,也可以自行去掉):
public static String bytesToHexString(byte[] src){
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
stringBuilder.append(i + ":");
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv + ";");
}
return stringBuilder.toString();
}
16进制字符串转化为二进制数据:
public static byte[] hexStringToByte(String hex) {
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
}
return result;
}
private static byte toByte(char c) {
byte b = (byte) "0123456789abcdef".indexOf(c);
return b;
}
标签:src,进制,16,二进制,hex,len,int,byte
From: https://blog.51cto.com/chengzheng183/6368268