Paulo Aquino

Ranch Hand

Posts: 202

posted 12 years ago

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?

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?

Be Afraid...Be very Afraid...

Yingtao Jiang

Greenhorn

Posts: 13

posted 12 years ago

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.

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.

SCJP1.4<br />SCJD1.4 (preparing)

John Wolf

Ranch Hand

Posts: 64

Don't get me started about those stupid light bulbs. |