意外的右移操作员行为

时间:2016-04-19 00:04:22

标签: javascript arithmetic-expressions

请查看以下Node.js REPL输出:

{{#link-to 'artist' artist.id}}Artist page{{/link-to}}

这是按预期工作的。现在看看这个:

> n=10
10
> console.log(n.toString(2)); //ok ?
1010
undefined
> m=n>>1 
5
> console.log(m.toString(2)); //cool :)
101

这里发生了什么?我不应该正确转移

> n=Number.MAX_VALUE 1.7976931348623157e+308 > m=n>>1 0 > n.toString(16) // to read easier 'fffffffffffff800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' > m.toString(16) // to read easier '0'

以1位数字给我

fffffffffffff800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

我是如何获得零的呢?

另外,我注意到它不仅仅是V8 / Node问题。我在Firebug中得到了相同的结果。

2 个答案:

答案 0 :(得分:2)

Javascript的位级操作仅适用于32位有符号值(或者在零扩展>>>运算符的情况下无符号值)。在进行位操作之前,将高于这32位的任何值设置为零。

答案 1 :(得分:1)

在JavaScript中,当您计算x >> y时,x将转换为带符号的32位整数。然后它被y个地方向右移动。

您的值0xfffffffffffff8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000转换为0x00000000,因为它们是最低的32位。右移这给零。