<分区>
我正在测试 Java 中的按位非运算符。我用二进制打印出 ~1 的结果,它返回“11111111111111111111111111111110”,显然计算结果为 -2。
我知道你必须加 1 才能得到 -1 并且最左边的位只显示数字是正数还是负数,但我不明白的是为什么二进制数那么大而且有那么多1s 的计算结果仅为 -2。
<分区>
我正在测试 Java 中的按位非运算符。我用二进制打印出 ~1 的结果,它返回“11111111111111111111111111111110”,显然计算结果为 -2。
我知道你必须加 1 才能得到 -1 并且最左边的位只显示数字是正数还是负数,但我不明白的是为什么二进制数那么大而且有那么多1s 的计算结果仅为 -2。
最佳答案
11111111111111111111111111111110
是原始位表示。 Java 使用 two's complement用于有符号值表示,其中第一位(如果设置)表示负数。
Conversion from Two's Complement 很好地解释了这一点:
Use the number 0xFFFFFFFF as an example. In binary, that is:
1111 1111 1111 1111 1111 1111 1111 1111
What can we say about this number? It's first (leftmost) bit is 1, which means that this represents a number that is negative. That's just the way that things are in two's complement: a leading 1 means the number is negative, a leading 0 means the number is 0 or positive.
To see what this number is a negative of, we reverse the sign of this number. But how to do that? The class notes say (on 3.17) that to reverse the sign you simply invert the bits (0 goes to 1, and 1 to 0) and add one to the resulting number.
The inversion of that binary number is, obviously:
0000 0000 0000 0000 0000 0000 0000 0000
Then we add one.
0000 0000 0000 0000 0000 0000 0000 0001
So the negative of
0xFFFFFFFF
is0x00000001
, more commonly known as1
. So0xFFFFFFFF
is-1
.
上面说明了为什么 0xFFFFFFFF
的二进制补码(如反向位加一)中的负数是 1
,这意味着它本身 0xFFFFFFFF
表示 -1
。以同样的方式,你的 0xFFFFFFFE
的值有 2
的负数,所以 0xFFFFFFFE
本身意味着 -2
的二分之一补充。
关于java - 11111111111111111111111111111110 如何计算为 -2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53654851/