There are three shift operators.
Left shift operator: it shifts left by num positions and fill with zeros on the right.
value << num
System.out.println(10 << 2);
Right shift operator: it shifts right by num positions, but the sign is preserved by filling on the left with the content of the previous leftmost bit.
System.out.println(-8 >> 2);
Unsigned right shift operator: it shifts right by num positions, but the sign is not preserved and fills on the left with zeros. For this reason, it's considered a logical operator, whereas the other two are arithmetic operators.
System.out.println(-8 >>> 2);
You can only shift long and int, the other primitives undergo promotion first.
There are practical uses in cryptography, communication protocols or for any byte manipulation. Imagine you need to store two short (16 bits each) in one int (32 bits):
short left = 12;
short right = 4;
int value = (left << 16) | right;
"Value" will contain:
0000000000001100 0000000000000100
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.