How do shift operators work in Java? [duplicate]
I am trying to understand the shift operators and couldn't get much. When I tried to execute the below code
System.out.println(Integer.toBinaryString(2 << 11));
System.out.println(Integer.toBinaryString(2 << 22));
System.out.println(Integer.toBinaryString(2 << 33));
System.out.println(Integer.toBinaryString(2 << 44));
System.out.println(Integer.toBinaryString(2 << 55));
I get the below
1000000000000
100000000000000000000000
100
10000000000000
1000000000000000000000000
Could somebody please explain?
Solution 1:
System.out.println(Integer.toBinaryString(2 << 11));
Shifts binary 2(10
) by 11 times to the left. Hence: 1000000000000
System.out.println(Integer.toBinaryString(2 << 22));
Shifts binary 2(10
) by 22 times to the left. Hence : 100000000000000000000000
System.out.println(Integer.toBinaryString(2 << 33));
Now, int is of 4 bytes,hence 32 bits. So when you do shift by 33, it's equivalent to shift by 1. Hence : 100
Solution 2:
2 from decimal numbering system in binary is as follows
10
now if you do
2 << 11
it would be , 11 zeros would be padded on the right side
1000000000000
The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension [..]
left shifting results in multiplication by 2 (*2) in terms or arithmetic
For example
2 in binary 10
, if you do <<1
that would be 100
which is 4
4 in binary 100
, if you do <<1
that would be 1000
which is 8
Also See
- absolute-beginners-guide-to-bit-shifting