Why does bitwise quot;not 1quot; equal -2?(为什么按位“不是 1?等于-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个整数: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; }
这篇关于为什么按位“不是 1"?等于-2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么按位“不是 1"?等于-2?


基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01