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;
}