Sunday, March 24, 2013

Shift operator in java

Shift operator in java


Java supports two types of shift operator (Logical Shift and Arithmetic shift).

Logical Shift: In logical shift simply all the bits except the extreme left or right bit is moved by one place. and The extra bit from the other end is replaced with zero.

For Example for The number 4 (binary = 0000 0100)

Logical Shift ( >>>, << )
                             original number       0000 0100              (Decimal 4)
                             after left shift           000 0100 0             (Decimal 8)


                             original number         0000 0100            (Decimal 4)
                             after left shift             0000 0010            (Decimal 2)

Java logical left shift operator is represented by (<<) and right shift operator is represented by (>>>)

Example,


11000000 >>> 2 = 0011000000 
01000000 << 2 = 00000000


Arithmetic shift : Signed Left Shift/ Signed Right Shift (>>,<<)
Arithmetic left shift is just like Logical Left shift, so in fact we do not have any special Logical Left Shift operator.

Arithmetic right shift is somewhat different then Logical right shift, as Arithmetic right shift will honor the most significant bit(MSB).


Example,



11000000 >> 2 = 11110000
01000000 >> 2 = 00010000


2's Complement

Step I)
To invert it by replacing all the 1s by 0 and 0s by 1.
So we get 00000000000000000000000000000 101 ---> 11111111111111111111111111111 010

Step II)
Now we have to add 1 to the no which we found in (I)
So we get ,
11111111111111111111111111111 010 + 1 = 11111111111111111111111111111 011


So the no 11111111111111111111111111111 011 represents -5 .
As the MSB i.e. the first bit is 1 , it indicates that the no. represents a -ve no.

No comments :

Post a Comment