To understand the Unsigned right shift (>>>) in JavaScript

315 阅读1分钟

What's the difference between right shift(>>) and Unsigned right shift(>>>)

In fact, the right shift(>>) is the Arithmetic shift and the Unsigned right shift is the Logical shift.

The difference is a logical shift does not preserve a number's sign bit.

In order to do the bitwise operation, the decimal representation must be transformed into a two's complement internally first.

The process of 5>>>2=15 >>> 2 = 1

The positive number is the same in both sign-magnitude and two's complement representation, so it's pretty easy:

  1. 510000000000000000000000000000001015_{10} \to 00000000000000000000000000000101 in both sign-magnitude and two's complement representation.
  2. Logical shift: 0000000000000000000000000000010100000000000000000000000000000010100000000000000000000000000000101 \to \underrightarrow{00}00000000000000000000000000001\cancel{01}
  3. The result is 1101_{10}

The process of 5>>>2=107374182210-5 >>> 2 = 1073741822_{10}

  1. 510000000000000000000000000000001015_{10} \to 00000000000000000000000000000101 in sign-magnitude representation
  2. 51010000000000000000000000000000101-5_{10} \to \underline{1}0000000000000000000000000000101 in sign-magnitude representation
  3. Convert the sign–magnitude representation to two's complement one via Working from LSB towards MSB which is more clear than from the one's complement: 100000000000000000000000000001011111111111111111111111111111101110000000000000000000000000000101 \to \underline{1}111111111111111111111111111101\underline{1}.
  4. Logical shift: 11111111111111111111111111111011001111111111111111111111111111101111111111111111111111111111111011 \to \underrightarrow{00}111111111111111111111111111110\cancel{11}
  5. Convert from two's complement representation to decimal via the following formula: w=aN12N1+i=0N2ai2iw = -a_{N-1}2^{N-1} + \sum_{i=0}^{N-2}a_i2^i
  6. The result is 1073741822101073741822_{10}

The process of 9>>>2=107374182110 -9 >>> 2 = 1073741821_{10}

  1. 910000000000000000000000000000010019_{10} \to 00000000000000000000000000001001 in sign-magnitude
  2. 91010000000000000000000000000001001-9_{10} \to \underline{1}0000000000000000000000000001001 in sign-magnitude
  3. 100000000000000000000000000010011111111111111111111111111111011110000000000000000000000000001001 \to \underline{1}111111111111111111111111111011\underline{1} in two's complement
  4. 11111111111111111111111111110111001111111111111111111111111111011111111111111111111111111111110111 \to \underrightarrow{00}111111111111111111111111111101\cancel{11}
  5. The result is 1073741821101073741821_{10}