20 May 2010

Shift operators in Java

Here's a very simple lesson that illustrate the shift operators in java

http://www.sap-img.com/java/java-bitwise-shift-operators.htm

Summary:

We have three shift operators in java >>, >>> and <<

1- >>
definition:
right shift with the outermost (hi bit) value
example:
9>> 2
9 in binary is 0000000000001001
so, we need to shift right 2 bites adding instead 2 bits of the hi bit
so, result will be 0000000000000010

2- >>>
It is the same as the above, but adds 0 at the left most (not the hi bit)
so, suppose we have
-1 >> 2
-1 in binary is 1111111111111111 (the 2's complement of 1)
so, the result will be -1 also. but if we applied >>> instead, we will always add 0's to the left of the bit pattern.

3- <<
left right is the oposite to the left shift (<<), that add the hi bit from the right.
ex:
9 << 1
9 in binary is 0000000000001001
result will be 0000000000010010 (in decimal is 18 )

(please let me know if there's any errors because I wrote that conclusion in hurry ;) )
Post a Comment