简体   繁体   中英

I add two numbers with the same way but get different values

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM