Shift Operators
suggest changeBitwise shifting moves the bits of a value left or right. The left operand is converted to a 32-bit integer (>>> uses an unsigned conversion). The shift count is converted to an unsigned integer and then used modulo 32.
Left Shift
The left shift operator (value) << (shift amount) will shift the bits to the left by (shift amount) bits; the new bits coming in from the right will be 0’s:
5 << 2; // 20
// 5: 00000101
// 20: 00010100 (two 0 bits enter from the right)
Right Shift (Sign-propagating)
The right shift operator (value) >> (shift amount) is also known as the “Sign-propagating right shift” because it keeps the sign of the initial operand. The right shift operator shifts the value the specified shift amount of bits to the right. Excess bits shifted off the right are discarded. The new bits coming in from the left will be based on the sign of the initial operand. If the left-most bit was 1 then the new bits will all be 1, and vice versa for 0.
20 >> 2; // 5
// 20: 00010100
// 5: 00000101
-5 >> 3; // -1
// -5: 11111011
// -1: 11111111
Right Shift (Zero fill)
The zero-fill right shift operator (value) >>> (shift amount) will move the bits to the right, and the new bits will be 0’s. The 0’s are shifted in from the left, and excess bits to the right are shifted off and discarded. This means it can make negative numbers into positive ones.
-30 >>> 2; // 1073741816
// -30 as Int32: 11111111 11111111 11111111 11100010
// 1073741816 as Int32: 00111111 11111111 11111111 11111000
For values in the range 0 through 2147483647, zero-fill right shift and sign-propagating right shift yield the same result. Larger numbers are converted to 32-bit integers first, so a positive value above that range can become negative before the shift.