Reputation: 1007
Please look at the following Node.js REPL output:
> n=10
10
> console.log(n.toString(2)); //ok ?
1010
undefined
> m=n>>1
5
> console.log(m.toString(2)); //cool :)
101
This is working as expected. Now look at this:
> 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'
What just happened here? Shouldn't me right shifting
fffffffffffff800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
by 1 digit give me
7ffffffffffffc00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
How did I get a zero instead?
Also, I noticed that it is not just V8/Node issue. I get the same result in Firebug.
Upvotes: 0
Views: 49
Reputation: 339916
Javascript's bit-level operations only work on 32-bit signed values (or unsigned in the case of the zero-extending >>>
operator). Anything above those 32 bits is set to zero before the bit operation takes place.
Upvotes: 2
Reputation: 18542
In JavaScript when you compute x >> y
, x
is converted into a signed 32-bit integer. Then it is shifted right by y
places.
Your value 0xfffffffffffff800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 is converted into 0x00000000 because those are the lowest 32 bits. Right shifting this gives zero.
Upvotes: 1