programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Please clarify this bitwise shifting

Karthik Balasubramanian
Ranch Hand
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
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
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

Karthik Balasubramanian
Ranch Hand
Posts: 43
Thanks Jose and chichih. It really helped me.

Karthik

 Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters?