I run into a problem today, here is the snippet:

Output:

Why `-101 >> 1`

is `-110011`

instead of `-110010`

?

Here is what I learned by reading **Professional JavaScript for Web Developers**:

When js stores a negative number, it does the following things:

- get the binary representation of the absolute value of the negative number
- replace 0s with 1s and 1s with 0s
- add 1 to the result of step 2

So in my case -101 >> 1, we first convert -101 to its binary representation:

The binary representation of Math.abs(-101) is:

invert the 0s and 1s:

add 1 to the end:

Now, shift it to the right by 1:

The binary above should be the correct result of -101 >> 1, but when logging a negative number's binary representation, Javascript simply puts a negative sign in front of the binary representation of the positive number:

For our example, this means that when logging the result of -101 >> 1, JS will output minus sign + the binary representation of the positive number. But the positive number is not 101 >> 1 because 101 >> 1 gives you:

To get the correct result, we have to reverse the aforementioned step 1-3:

Reverse step 3 by subtracting 1, we get:

Reverse step 2 by invert 0s and 1s:

Reverse step 1 by converting this binary to integer:

Finally, when JS logs the result of -101 >> 1, it should be in the format of minus sign + the binary representation of 51: