我研究了Java中从String到hex字节数组的转换。从字符串转换为hexString,从hexString转换为字节数组的例子有很多。我想知道String.getbyte()与从String转换为hexString到字节数组之间的区别吗?
我相信它类似于:
byte[] bytes = "Apple".getBytes();
和
String hexStringSample = stringToHex("Apple");
byte[] bytes2 = hexStringToByteArray(hexStringSample);
public static String stringToHex(String s) {
String result = "";
for (int i = 0; i < s.length(); i++) {
result += String.format("%02x ", (int) s.charAt(i));
}
return result;
}
//hexStringToByteArray
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;
}