Java中的字节数组和Int转换 [英] Byte Array and Int conversion in Java
问题描述
我在使用这两个函数时遇到了一些困难: byteArrayToInt
和 intToByteArray
。
I am having some difficulty with these two functions: byteArrayToInt
and intToByteArray
.
问题在于,如果我使用一个到达另一个并且结果到达前者,结果会有所不同,正如您从下面的示例中看到的那样。
The problem is that if I use one to get to another and that result to get to the former, the results are different, as you can see from my examples below.
我在代码中找不到错误。任何想法都非常受欢迎。谢谢。
I cannot find the bug in the code. Any ideas are very welcome. Thanks.
public static void main(String[] args)
{
int a = 123;
byte[] aBytes = intToByteArray(a);
int a2 = byteArrayToInt(aBytes);
System.out.println(a); // prints '123'
System.out.println(aBytes); // prints '[B@459189e1'
System.out.println(a2); // prints '2063597568
System.out.println(intToByteArray(a2)); // prints '[B@459189e1'
}
public static int byteArrayToInt(byte[] b)
{
int value = 0;
for (int i = 0; i < 4; i++) {
int shift = (4 - 1 - i) * 8;
value += (b[i] & 0x000000FF) << shift;
}
return value;
}
public static byte[] intToByteArray(int a)
{
byte[] ret = new byte[4];
ret[0] = (byte) (a & 0xFF);
ret[1] = (byte) ((a >> 8) & 0xFF);
ret[2] = (byte) ((a >> 16) & 0xFF);
ret[3] = (byte) ((a >> 24) & 0xFF);
return ret;
}
推荐答案
你正在交换 endianness 。你有 intToByteArray(int a)
将低位比特分配到 ret [0]
,但随后 byteArrayToInt(byte [] b)
将 b [0]
分配给结果的高位。你需要反转其中一个,比如:
You're swapping endianness between your two methods. You have intToByteArray(int a)
assigning the low-order bits into ret[0]
, but then byteArrayToInt(byte[] b)
assigns b[0]
to the high-order bits of the result. You need to invert one or the other, like:
public static byte[] intToByteArray(int a)
{
byte[] ret = new byte[4];
ret[3] = (byte) (a & 0xFF);
ret[2] = (byte) ((a >> 8) & 0xFF);
ret[1] = (byte) ((a >> 16) & 0xFF);
ret[0] = (byte) ((a >> 24) & 0xFF);
return ret;
}
这篇关于Java中的字节数组和Int转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!