Bitwise operations in JavaScript

4

I know that numbers in JavaScript are stored in IEEE-754 format. But when we use integers, particularly bitwise operators, they're represented as two's complement with 32 bits.

So -1 would be 0xFFFFFFFF. But (-1).toString(2) is -1. And -1 >>> 31 is 1, that's right, but -1 >>> 32 must be 0, however it's 4294967295. And -1 << 32 must be 0, but it is -1.

Why do bitwise operations work in this way? And toString() shows number with sign -, why this minus is not in sign bit? Also why -1 >> 0 is -1, but -1 >>> 0 is 4294967295? I know what is the difference between >> and >>>, but the second operand is 0, so I can't understand why these operations work in different ways.

javascript
bitwise-operators
asked on Stack Overflow Feb 19, 2020 by Sergei Martianov • edited Feb 19, 2020 by Heretic Monkey

1 Answer

3

Difference between >>> and >>

In an arithmetic shift, the sign bit is extended to preserve the signedness of the number.

-1 in 8 bit is 11111111 -2 is 11111110 ...

This is handled like that because if you count to the highest possible number +1, the lowest possible number will be shown (8 bit: 01111111 +1 = 10000000), Thats why 111111111 is -1

Logical right shift, however, does not care that the value could possibly represent a signed number; it simply moves everything to the right and fills in from the left with 0s.

so here, -1 >>> pushes the 11111111 one to the right so the "-" sign gets lost and the highest positive number 0111111 (in 8 bit) is shown

Also the reason why -1 >> 0 equals -1 is because 11111111 >> 0 does literally add nothing while -1 >>> 0 still moves everything and fills the left bits with 0, each step you raise this "0" will half the value until 0. You can try -1 >>> 31 to see it gets 1

answered on Stack Overflow Feb 19, 2020 by Updater • edited Feb 19, 2020 by Updater

User contributions licensed under CC BY-SA 3.0