2016-04-19 59 views
0

請看看下面的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中得到了相同的結果。

+0

我想你想['Number.MAX_SAFE_INTEGER'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER) –

+0

@HunterMcMillen居然,不,因爲那個範圍是53位,但是位操作只能工作在32位 – Alnitak

回答

1

在JavaScript中,當你計算x >> y時,x被轉換爲帶符號的32位整數。然後它被右移y的地方。

你的值0xfffffffffffff800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000被轉換成0×00000000,因爲這些都是最低的32位。右移這給零。

+0

啊!這現在非常有意義。 – anu

2

Javascript的位級操作只能用於32位有符號值(或在零延伸操作符的情況下無符號)。在發生位操作之前,高於這些32位的任何位都會置零。