简体   繁体   English

我以相同的方式添加两个数字,但得到的值不同

[英]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. 从逻辑上讲, ij是相同的,但是我得到的结果非常惊人。

Results: 结果:

27
230
6912
230.0
7142.0

i and j should be the same but it isn't. ij应该相同,但事实并非如此。 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 . 在Java中, 按位&运算符的优先级低于+运算符 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); 因此, i实际上定义为((bytes[1] & 0xFF)*256 + bytes[0])& 0xFF ,其结果为230,而不是预期的7142。用i = (bytes[1] & 0xFF)*256 + (bytes[0] & 0xFF); is all you need to do. 这就是您需要做的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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