为什么按位“不是 1"?等于-2?

2022-01-17 00:00:00 numbers bitwise-operators javascript

假设我们有 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个整数:0-1

1  二进制是 000000000000000000000000000000001
0  二进制是 000000000000000000000000000000000
-1 二进制是 11111111111111111111111111111111
-2 二进制是 1111111111111111111111111111110
("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; }

相关文章