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

> 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'


刚刚发生什么事了?我不应该右移

fffffffffffff800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

1位数给我

7ffffffffffffc00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

我怎么变成零呢?

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

最佳答案

在JavaScript中,当您计算x >> y时,x会转换为带符号的32位整数。然后将其右移y个位置。

您的值0xfffffffffffff800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000因为这是最低的32位右移将得到零。

关于javascript - 意外的右移运算符(operator)行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36706302/

10-12 14:10