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 二进制是 0000000000000000000000000000000010 二进制是 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?
- Fetch API 如何获取响应体? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Flexslider 箭头未正确显示 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
