为什么Integer.MIN_VALUE的负数给出相同的值? [英] Why does the negative of Integer.MIN_VALUE give the same value?
问题描述
考虑以下Java代码.
Consider the below java code.
Integer value = Integer.MIN_VALUE;
System.out.println(value);
value = -value;
System.out.println(value);
输出
-2147483648
-2147483648
Integer.MIN_VALUE
值的负值如何产生相同的值?
但是结果不能为2147483648
,因为java中Integer的最大值为2147483647
.
How the negative value of Integer.MIN_VALUE
value results the same value?
However the result can't be 2147483648
because the maximum value of Integer in java is 2147483647
.
但是想知道为什么-2147483648
吗?内部正在发生哪种按位运算?
But want to know why -2147483648
? What kind of bit-wise operations are happening internally?
推荐答案
内部发生了什么样的按位运算?
What kind of bit-wise operations are happening internally?
Java使用带符号的数字的二进制补语表示.因此,更改符号操作包括两个步骤:
Java uses two's complement representation of signed numbers. Therefore, the change of sign operation, consists of two steps:
- 反转原始值的位,并且
- 将
1
添加到结果中.
- Inverting the bits of the original value, and
- Adding
1
to the result.
2147483648
的表示如下所示:
10000000000000000000000000000000
将其反转产生
01111111111111111111111111111111
添加1
会使它再次成为相同的数字,即
Adding 1
makes it the same number again, i.e.
10000000000000000000000000000000
由于整数溢出.
这篇关于为什么Integer.MIN_VALUE的负数给出相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!