为什么移位24位会导致负值?

Kam*_*ski 3 javascript bitwise-operators

当我对小于256的数字执行24位移位时,得到否定结果吗?这是为什么?

console.log( (200<<23)>>23 );

console.log( (200<<24)>>24 ); // ???
Run Code Online (Sandbox Code Playgroud)

Nie*_*sol 5

Since bit shifts work in binary, let's look at the binary representation. 32 bits are used for those operators.

Decimal    | Binary
200        | 0000 0000 0000 0000 0000 0000 1100 1000
Run Code Online (Sandbox Code Playgroud)

Now shift left 24 places...

200        | 0000 0000 0000 0000 0000 0000 1100 1000
-939524096 | 1100 1000 0000 0000 0000 0000 0000 0000
Run Code Online (Sandbox Code Playgroud)

Most importantly, notice how the first bit is now a 1, which indicates a negative number in signed 32-bit numbers.

The next thing to note is that >> is a sign-propagating right shift. This means that when you shift right again, you are shifting in copies of the first bit.

-939524096 | 1100 1000 0000 0000 0000 0000 0000 0000
-56        | 1111 1111 1111 1111 1111 1111 1100 1000
Run Code Online (Sandbox Code Playgroud)

However if you use >>> instead, you get a zero-fill right shift. As the name implies, it always shifts in 0s.

-939524096 | 1100 1000 0000 0000 0000 0000 0000 0000
200        | 0000 0000 0000 0000 0000 0000 1100 1000
Run Code Online (Sandbox Code Playgroud)