The Java language provides three operator for performing bitwise shifting on 32 and 64 bit integer values. These are all binary operators with the first operand being the value to be shifted, and the second operand saying how far to shift.
<< or left shift operator shifts the value given by the first operand leftwards by the number of bit positions given by the second operand. The empty positions at the right end are filled with zeros.
The '>>' or arithmetic shift operator shifts the value given by the first operand rightwards by the number of bit positions given by the second operand. The empty positions at the left end are filled by copying the left-most bit. This process is known as sign extension.
The '>>>' or logical right shift operator shifts the value given by the first operand rightwards by the number of bit positions given by the second operand. The empty positions at the left end are filled with zeros.
These operators require an
long value as the first operand, and produce a value with the same type as the first operand. (You will need to use an explicit type cast when assigning the result of a shift to a
If you use a shift operator with a first operand that is a
short, it is promoted to an
int and the operation produces an
The second operand is reduced modulo the number of bits of the operation to give the amount of the shift. For more about the mod mathematical concept, see Modulus examples.
The bits that are shifted off the left or right end by the operation are discarded. (Java does not provide a primitive "rotate" operator.)
The arithmetic shift operator is equivalent dividing a (two's complement) number by a power of 2.
The left shift operator is equivalent multiplying a (two's complement) number by a power of 2.
The following table will help you see the effects of the three shift operators. (The numbers have been expressed in binary notation to aid vizualization.)
There examples of the user of shift operators in Bit manipulation