Difference between right shift and zero fill shift in javascript?

As I know,

Right shift (a โ†’ b): Shifts a bit in the binary representation of b bits to the right, discarding the bit shifted.

Ex: 8 โ†’ 2 will return 2. therefore binary 1000 will shift 2 times to the right and return 0010.

Zero padding offset (a โ†’> b): Shifts a bit in the binary representation of b bits to the right, discards bits shifted down, and shifts zeros to the left.

Ex: 8 -> 2 return 2.it also reconfigure the same.

then what is the difference between the >> and >>> operator and why does javascript have these two operators and not one, or if I am wrong, please help me to get the correct concept?

+6
source share
1 answer

Bitwise operators assume that their operands are 32-bit signed integers.

00000000000000000000000000001000 in base 2 is 8 in base 10.


In 8 >> 2 sign-shifting operator shift-right (โ†’) shifts the binary number two places, preserving the sign (which is the first bit):

00000000000000000000000000000010 in base 2 is 2 in base 10.

In 8 >>> 2 , the zero fill change operator (โ†’>) shifts the binary number two places, filling the left bits 0s:

00000000000000000000000000000010 in base 2 equals 2 in base 10

They are identical, simply because the first bit for positive binary numbers is zero.

From MDN :

For non-negative numbers, a zero shift to the right and a right shift sign give the same result.


However, for negative numbers, everything looks different:

11111111111111111111111111111000 in base 2 is equal to -8 in base 10.

In -8 >> 2 operator that moves the shift sign (โ†’) shifts the binary number two places, preserving the sign:

11111111111111111111111111111110 in base 2 is -2 in the base 10.

In -8 >>> 2 , the zero-fill offset operator (โ†’>) shifts the binary number two places, filling the left bits 0s:

00111111111111111111111111111110 in base 2 is 1073741822 in base 10.

+6
source

Source: https://habr.com/ru/post/984399/


All Articles