admin管理员组

文章数量:1287809

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?

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?

Share Improve this question asked Mar 29, 2015 at 18:55 Mukund KumarMukund Kumar 23.2k20 gold badges63 silver badges84 bronze badges 2
  • 1 Try -8 >> 2: -2 vs. -8 >>> 2: 1073741822 – Rick Hitchcock Commented Mar 29, 2015 at 19:04
  • 1 developer.mozilla/en-US/docs/Web/JavaScript/Reference/… can give you the correct answer – invernomuto Commented Mar 29, 2015 at 19:13
Add a ment  | 

1 Answer 1

Reset to default 13

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.

本文标签: difference between Signpropagating right shift and Zerofill right shift in javascriptStack Overflow