Shift Operators are used to shift the bits of a number left or right thereby multiplying or dividing the number by two respectively.
- Left shift operator (<<) : Shifts the bits of the number to the left and fills 0 (zero) on left as a result.
- Signed Right shift operator (>>): Shifts the bits of the number to the right. The leftmost bit depends on the sign of number.
- Unsigned Right shift operator (>>>): Shifts the bits of the number to the right and fills 0 (zero) on left.
>>>
will always put a 0 in the left most bit, while >>
will put a 1 or a 0 depending on what the sign of the number.
For example: -2 represented in 8 bits would be 11111110 (because the most significant bit has negative weight). Shifting it right one bit using >>
would give 11111111, or -1. >>>
moves everything to the right and fills in from the left with 0s. Shifting -2 right one bit using >>>
would give 01111111.