File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Please clarify this bitwise shifting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Please clarify this bitwise shifting" Watch "Please clarify this bitwise shifting" New topic

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);
Answer is :
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?
Thanks in advance,
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
int i = 1;
0000 0001
i <<= 31;
8000 0000
i >>= 31;
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

SCJP2. Please Indent your code using UBB Code
chi Lin
Ranch Hand

Joined: Aug 24, 2001
Posts: 348
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.

I agree. Here's the link:
subject: Please clarify this bitwise shifting
Similar Threads
Shift operator....
Shift operator doubt
shift question
Doubt in Shift operator