Reputation: 37
According to Wikipedia the js arithmetic shift right and left operators are <<
and >>
and while the left shift seems to be working correctly, the right shift seems to be doing a bitwise shift rather than a arithmetic one
> 2 >> 1
1
> 2 << 1
4
> 1 >> 1
0
> 1 << 1
2
how can i get an arithmetic shift?
Upvotes: 1
Views: 521
Reputation: 1856
I'm not sure what values you are expecting. An arithmetic bit shift is what JavaScript does, but you will never see it without using negative values.
For example:
-1 >> 1 === -1
or
-20 >> 1 === -10
If these were standard logical bit shifts instead, the result would be dependent on the bit depth of the values, and not meaningful in the context of JavaScript. For example, the difference between logical and arithmetic bit shift in 8-bit (to keep it simple):
-1 would be 1111 1111:
1111 1111 arithmethic shift right = 1111 1111 (still -1, the high bit is "sticky")
1111 1111 logical shift right = 0111 1111 (now 127)
Edit: In JS, if you want to use a logical shift right, you can use >>> instead of >>. It works on 32-bit integers when you do. So:
-1 >>> 1 === 2147483647
Upvotes: 3