二進制數據一般輸入的格式是0x45, 0x3a, 0xc3, 這種數據格式看起來是16進制的字符串,但是實際上在存儲的時候每個都對應一個字節,比如0x45的二進制字節就是0100 0101,對應的16進制字符串就是0x45。實際編程過程中,經常遇到這兩種格式的相互轉化,在此記錄一下代碼。
二進制數據轉化爲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;
}