Why does -3 >> 1 equal -2?

Viewed 118

In JS, we have the following situation:

<< operator:

3 << 1  // 6
5 << 1  // 10
7 << 1  // 14
-3 << 1 // -6
-5 << 1 // -10
-7 << 1 // -14

>> operator:

3 >> 1  // 1
5 >> 1  // 2
7 >> 1  // 3
-3 >> 1 // -2
-5 >> 1 // -3
-7 >> 1 // -4

As you can see, for the << operator, and for values less than 2**32, we have abs(X << Y) === abs(-X << Y).

Why doesn't this keep true for the >> operator?

2 Answers

Because you are rotating the binary representation of those numbers. And the negative numbers are stored as 2's complement binary

So (using just 8-bits for illustration purposes):

-3 = 11111101

Which if you rotate with >> which is sign propagating you will get:

11111110 = -2

Because the sign propagating shift copies the sign bit to the left-most bit.

With the positive numbers it's easier:

3 = 00000011

After shifting with >> (since it's positive, you are shifting in zeros)

00000001 = 1

It's because minus has greater precedence than shift operator.

So, -3 >> 1 will run as (-3) >> (1) but not as -(3 >> 1).

Related