以下是我在java和python中尝试进行转换的示例代码。我是这个概念的新手。为什么我会得到不同的价值?我怎样才能获得与python中java相同的值?
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;
}
output :[B@57829d67
In python I tried:
test = bytearray.fromhex("4BE7C580")
output : bytearray(b'K\xe7\xc5\x80')
答案 0 :(得分:0)
似乎没错。
public static void main(String[] args) {
byte[] array = hexStringToByteArray("4BE7C580");
System.err.println(Arrays.toString(array));
for (byte b : array) {
System.err.println(Integer.toHexString(b & 0xff));
}
}
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;
}
给出
[75, -25, -59, -128]
4b
e7
c5
80