假设我们有1
这个以 2 为基数的数字是:
00000000000000000000000000000001
现在我想翻转所有位以获得以下结果:
11111111111111111111111111111110
据我所知,解决方案是使用~
(按位非运算符)翻转所有位,但结果~1
is -2
:
console.log(~1); //-2
console.log((~1).toString(2)); //-10 (binary representation)
为什么我会得到这个奇怪的结果?
之间有2个整数1
and -2
: 0
and -1
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
equals -2
, since ~0
equals -1
.
As @Derek https://stackoverflow.com/users/283863 解释了 https://stackoverflow.com/questions/31377474/why-does-bitwise-not-1-equal-2/31377545#comment50734070_31377545, These 按位运算符 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators将它们的操作数视为 32 位序列。parseInt
,另一方面,则不然。这就是为什么你会得到一些不同的结果。
这是一个更完整的演示:
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; }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)