This week's book giveaway is in the OCAJP 8 forum.We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!See this thread for details.
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!

# Please clarify this bitwise shifting

Karthik Balasubramanian
Ranch Hand

Joined: Dec 13, 2002
Posts: 43
Hi all,
Look at the code below:
public class Temp {
public static void main (String args[]) {
int i = 1;
i <<= 31;
i >>= 31;
i >>= 1;
int j = 1;
j >>= 31;
j >>= 31;
System.out.println("i = " +i );
System.out.println("j = " +j);
}
}
i = -1
j = 0
I agree with the value of j. But how am I getting the value of -1?
Can some one explain this to me?
Katrhik
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
int i = 1;
0000 0001
i <<= 31;
8000 0000
i >>= 31;
FFFF FFFF
This the trick. >>= is a signed shift. It respect the sign of its operand. Because 8000 0000 is a negative number, 1s will be added to the left to keep the most significant bit to 1, and thus its negativeness.
>>= will add 0s if the MSB is 0
i >>= 1
FFFF FFFF= -1

chi Lin
Ranch Hand

Joined: Aug 24, 2001
Posts: 348
Karthink,
int i =1 -> 00000001
i<<=31, -> 10000000,
(right shift 31 bits, the number is negative because of the 1 on sign bit)
i>>=31, -> FFFFFFFF
(thrity-one ones filled in for right shift on negative number)
i>==1, -> still FFFFFFFF
(another 1 fill in)
so the result is -1,
Hope this help

not so smart guy still curious to learn new stuff every now and then
Karthik Balasubramanian
Ranch Hand

Joined: Dec 13, 2002
Posts: 43
Thanks Jose and chichih. It really helped me.

Karthik

I agree. Here's the link: http://aspose.com/file-tools

subject: Please clarify this bitwise shifting