Binary Shift Operators Example
There are 3 binary shift operators that shift the binary digits (bits) of a number left or right:<< (left shift)
>> (signed right shift)
>>> (unsigned right shift)
At run time, shift operations are performed on the two's complement integer representation of the value of the left operand.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Binary Shift Operators Example
class BinaryShiftOperators {
public static void main(String[] args) {
int i = 27;
i = i >> 2;
i = i << 4;
i = 27;
i = i >>> 2;
i = -27;
i = i >>> 2;
}
}
6 i is assigned the value 27. In simple binary this is 11011.
7 The bits of 27 (11011) are shifted right 2 to give the binary value 00110 ie the decimal value 6.
8 The bits of 6 (00110) are shifted left 4 to give the binary value 1100000 ie the decimal value 96.
11 The bits of 27 (11011) are unsigned shifted right 2 to give the binary value 00110 ie the decimal value 6.
14 The bits of -27 (11111111111111111111111111100101) are unsigned shifted right 2 to give the binary value 111111111111111111111111111001 ie the decimal value 1073741817.
