How do shift operators work in Java?

gnreddy picture gnreddy · Jun 6, 2012 · Viewed 235.4k times · Source

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?

Answer

Kazekage Gaara picture Kazekage Gaara · Jun 6, 2012
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