Bitwise shifting can be thought as "moving" the bits either left or right, and hence changing the value of the data operated on.
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: 0..000101
// 20: 0..010100 <= adds two 0's to the right
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 vise-versa for 0
's.
20 >> 2 => 5
// 20: 0..010100
// 5: 0..000101 <= added two 0's from the left and chopped off 00 from the right
-5 >> 3 => -1
// -5: 1..111011
// -2: 1..111111 <= added three 1's from the left and chopped off 011 from the right
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: 111..1100010
//1073741816: 001..1111000
Zero-fill right shift and sign-propagating right shift yield the same result for non negative numbers.