可能重複:
How does Java handle integer underflows and overflows and how would you check for it?
How is System.out.println(4*2147483647) equal to -4 in java?爲什麼2 * Integer.MAX_VALUE = -2?
我想知道爲什麼這樣認爲:
2 * Integer.MAX_VALUE == -2
我期待您的回覆。
可能重複:
How does Java handle integer underflows and overflows and how would you check for it?
How is System.out.println(4*2147483647) equal to -4 in java?爲什麼2 * Integer.MAX_VALUE = -2?
我想知道爲什麼這樣認爲:
2 * Integer.MAX_VALUE == -2
我期待您的回覆。
你得到這樣的結果,因爲integer overflow的:在代表負整數,取最大值是011.....11
和2
相乘的two's complement系統使您11.....110
,這相當於-2
。
這是因爲整數溢出。
Integer.MAX_VALUE
是0x7FFFFFFF
。乘以2,得到0xFFFFFFFE
(相當於左移一位)。這是一個負數(第一位是1),並且是-2
的二進制表示形式。
這是因爲二進制補碼,其中最左邊的位用來表示數字是正數(0)還是負數(1)。所以,當你本身(的multiplfy相當於由二)增加最大INT,出現這種情況:
011111111111111111111111
+ 011111111111111111111111
__________________________
111111111111111111111110
和111111111111111111111110
代表-2。
INT的MAX_VALUE是2^31-1 = 2147483647 = 0111 1111 1111 1111 1111 1111 1111 1111(二進制數)最高位(這裏是第一位0,表示整數是一個正數,當1表示負
(假設的整數的長度爲4字節)的比特,2 * MAX_VALUE,在計算機2倍的整數。左移(操作者< <),例如2 < < 1 = 4; 2。 < < 2 = 8;所以0111 1111 1111 1111 1111 1111 1111 1111 < < 1成爲1111 1111 1111 1111 1111 1111 1111 1110其等於-2十進制
[Integer overflow](http://en.wikipedia.org/wiki/Integer_overflow)。 – BalusC
請參閱這裏:http://stackoverflow.com/questions/3001836/how-does-java-handle-integer-underflows-and-overflows-and-how-would-you-check-fo –
很多downvotes。這是一個特別糟糕的問題嗎?固定整數運算是奇數(應該是模糊的)。 –