[英]I add two numbers with the same way but get different values
以下是代碼,我對獲得的結果感到非常困惑。
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
應該相同,但事實並非如此。 我不知道原因 有什么解釋嗎?
它們不是等效的。 在Java中, 按位&
運算符的優先級低於+
運算符 。 因此, i
實際上定義為((bytes[1] & 0xFF)*256 + bytes[0])& 0xFF
,其結果為230,而不是預期的7142。用i = (bytes[1] & 0xFF)*256 + (bytes[0] & 0xFF);
這就是您需要做的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.