Left shift and right shift operators in Java
A lot of time we use >> , >>> or << and <<< operators in Java for bit operations. These operations essentially shift bits left or right depending on the operator. In this post we will see what exactly is the difference.
- >> is arithmetic or signed shift right
- >>> is logical or unsigned shift right
- << is arithmetic or signed shift left
The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.
NOTE : There is no logic left shift as it is same as arithmetic left shift.
Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 | System.out.println(Integer.toBinaryString(- 121 )); // prints "11111111111111111111111110000111" System.out.println(Integer.toBinaryString(- 121 >> 1 )); // prints "11111111111111111111111111000011" System.out.println(Integer.toBinaryString(- 121 >>> 1 )); // prints "1111111111111111111111111000011" System.out.println(Integer.toBinaryString( 121 )); // prints "1111001" System.out.println(Integer.toBinaryString( 121 >> 1 )); // prints "111100" System.out.println(Integer.toBinaryString( 121 >>> 1 )); // prints "111100" |
As you can see in case of -121 since it is a negative number arithmetic or signed shift right adds a 1 to the rightmost bit where as in case if 121 it adds 0.
logical or unsigned shift does not care about sign. It just adds 0 to the shifted bits.
No comments:
Post a Comment