Reputation: 85
the following is the code and I am extremely confused with the results I get.
byte[] bytes = new byte[2];
bytes[0] = (byte)0xE6;
bytes[1] = (byte)0x1B;
int high = (bytes[1] & 0xFF)*256;
int low = bytes[0] & 0xFF;
double j = high + low;
double i = (bytes[1] & 0xFF)*256 + bytes[0] & 0xFF;
System.out.println(bytes[1] & 0xFF);
System.out.println(bytes[0] & 0xFF);
System.out.println((bytes[1] & 0xFF)*256);
System.out.println(i);
System.out.println(j);
Logically, i
and j
are the same but the result I get is quite amazing.
Results:
27
230
6912
230.0
7142.0
i
and j
should be the same but it isn't. I don't know the reason. Is there any explanation for this?
Upvotes: 2
Views: 69
Reputation: 4306
They aren't equivalent; In java, the bitwise &
operator has a lower precedence than the +
operator. So i
is actually being defined as ((bytes[1] & 0xFF)*256 + bytes[0])& 0xFF
, which evaluates to 230, instead of the intended 7142. Replacing that line with i = (bytes[1] & 0xFF)*256 + (bytes[0] & 0xFF);
is all you need to do.
Upvotes: 4