Java: 如何将这个 byte[] 反转为 hex 方法?
Java: How to reverse this byte[] to hex method?
我在网上找到了这个,它可以满足我的需要,但是我该如何反转它,也就是说如何将十六进制字符串转换回字节[]?
private static final char[] HEX_CHARS = {
'0', '1', '2' ,'3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f'
};
public String toHexString(byte[] bytes)
{
StringBuilder sb = new StringBuilder();
for(int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
sb.append(new char[] {HEX_CHARS[(b >> 4) & 0x0f], HEX_CHARS[b & 0x0f]});
}
return sb.toString();
}
尝试以下操作:
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
我在网上找到了这个,它可以满足我的需要,但是我该如何反转它,也就是说如何将十六进制字符串转换回字节[]?
private static final char[] HEX_CHARS = {
'0', '1', '2' ,'3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f'
};
public String toHexString(byte[] bytes)
{
StringBuilder sb = new StringBuilder();
for(int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
sb.append(new char[] {HEX_CHARS[(b >> 4) & 0x0f], HEX_CHARS[b & 0x0f]});
}
return sb.toString();
}
尝试以下操作:
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}