Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Shifting operators

Paulo Aquino
Ranch Hand
Posts: 202

int i = 1;
i <<= 31;//2
System.out.println(i);//3
i >>=31;//4
System.out.println(i);//5

Line 1 in binary is
0000 0000 0000 0000 0000 0000 0000 0001

Line 2 left shifts the value , in binary that's
1000 0000 0000 0000 0000 0000 0000 0000
So its value is -2147483648

Line 4 right shifts so it should be like this ?

1111 1111 1111 1111 1111 1111 1111 1111

I was wondering why the Line 5 prints -1?

Yingtao Jiang
Greenhorn
Posts: 13
That binary pattern IS -1.
Because it is 2's complement. As the sign bit(the left most) is 1, so it is a negative number, in order to calculate its absolute value, you can do the following:
bitwise negation first, then plus 1.
So the all 1 pattern will become 000000...01.

John Wolf
Ranch Hand
Posts: 64
Paulo,

Another way to see this is : -

10000000 00000000 00000000 00000000

is the smallest -ve number

11111111 11111111 11111111 11111111

is the largest -ve number ... hence -1

Cheers!~
Sumit