As i know,
Sign-propagating right shift (a >> b) : Shifts a in binary representation b bits to the right, discarding bits shifted off.
Ex: 8>>2 will return 2.because binary 1000 will shift 2 times right and return 0010.
Zero-fill right shift (a >>> b): Shifts a in binary representation b bits to the right, discarding bits shifted off, and shifting in zeros from the left.
Ex: 8>>2 return 2.it also retun the same.
then what is difference between >>
and >>>
operator and why javascript has these two operator instead of one or if i am wrong then please guide me to get right concept?
The bitwise operators assume their operands are 32-bit signed integers.
00000000000000000000000000001000
in base 2 equals 8
in base 10.
8 >> 2
, the sign-propagating shift-right operator (>>) shifts the binary number two places, preserving the sign (which is the first bit):
00000000000000000000000000000010
in base 2 equals 2
in base 10.
In 8 >>> 2
, the zero-fill right-shift operator (>>>) shifts the binary number two places, filling in the left bits with 0s:
00000000000000000000000000000010
in base 2 equals 2
in base 10
These are identical, simply because the first bit for positive binary numbers is a zero.
From MDN:
For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.
For negative numbers, however, things look different:
11111111111111111111111111111000
in base 2 equals -8
in base 10.
In -8 >> 2
, the sign-propagating shift-right operator (>>) shifts the binary number two places, preserving the sign:
11111111111111111111111111111110
in base 2 equals -2
in base 10.
In -8 >>> 2
, the zero-fill right-shift operator (>>>) shifts the binary number two places, filling in the left bits with 0s:
00111111111111111111111111111110
in base 2 equals 1073741822
in base 10.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With