为什么按位“不是1”等于-2? [英] Why does bitwise "not 1" equal -2?
问题描述
假设我们 1
,基数2中的这个数字是:
Suppose we have 1
and this number in base 2 is:
00000000000000000000000000000001
现在我要翻转所有位以获得以下结果:
Now I want to flip all bits to get following result:
11111111111111111111111111111110
目前为止据我所知,解决方案是使用〜
(按位NOT运算符)来翻转所有位,但结果为 ~1
是 -2
:
As far as I know, the solution is to use the ~
(bitwise NOT operator) to flip all bits, but the result of ~1
is -2
:
console.log(~1); //-2
console.log((~1).toString(2)); //-10 (binary representation)
为什么我会得到这个奇怪的结果?
Why do I get this strange result?
推荐答案
1
和 -2 2之间有2个整数code>:
0
和 -1
1
  二进制是 00000000000000000000000000000001
0
在二进制是 00000000000000000000000000000000
-1
二进制是 11111111111111111111111111111111
-2
二进制是 11111111111111111111111111111110
(binary是2的补码,在按位的情况下不是〜
)
1
in binary is 00000000000000000000000000000001
0
in binary is 00000000000000000000000000000000
-1
in binary is 11111111111111111111111111111111
-2
in binary is 11111111111111111111111111111110
("binary" being 2's complement, in the case of a bitwise not ~
)
如你所见,这并不奇怪 ~1
等于 -2
,因为〜0
等于 -1
。
As you can see, it's not very surprising ~1
equals -2
, since ~0
equals -1
.
正如 @Derek 解释,这些按位运算符将其操作数视为32位序列。另一方面, parseInt
则没有。这就是为什么你得到一些不同的结果。
As @Derek explained, These bitwise operators treat their operands as a sequence of 32 bits. parseInt
, on the other hand, does not. That is why you get some different results.
这是一个更完整的演示:
Here's a more complete demo:
for (var i = 5; i >= -5; i--) {
console.log('Decimal: ' + pad(i, 3, ' ') + ' | Binary: ' + bin(i));
if (i === 0)
console.log('Decimal: -0 | Binary: ' + bin(-0)); // There is no `-0`
}
function pad(num, length, char) {
var out = num.toString();
while (out.length < length)
out = char + out;
return out
}
function bin(bin) {
return pad((bin >>> 0).toString(2), 32, '0');
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于为什么按位“不是1”等于-2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!