Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between Sign-propagating right shift and Zero-fill right shift in javascript?

Tags:

javascript

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?

like image 732
Mukund Kumar Avatar asked Mar 29 '15 18:03

Mukund Kumar


1 Answers

The bitwise operators assume their operands are 32-bit signed integers.

00000000000000000000000000001000 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 (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.

like image 175
Rick Hitchcock Avatar answered Nov 16 '22 06:11

Rick Hitchcock