以下是代码,我对我得到的结果非常困惑。
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);
逻辑上,i
和j
是相同的,但我得到的结果非常惊人。
结果:
27
230
6912
230.0
7142.0
i
和j
应该相同但不是。我不知道原因。对此有任何解释吗?
答案 0 :(得分:4)
它们不等同;在java中,the bitwise &
operator has a lower precedence than the +
operator。因此,i
实际上被定义为((bytes[1] & 0xFF)*256 + bytes[0])& 0xFF
,其评估结果为230,而不是预期的7142.您需要用i = (bytes[1] & 0xFF)*256 + (bytes[0] & 0xFF);
替换该行。