aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Shifting operators Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Shifting operators" Watch "Shifting operators" New topic
Author

Shifting operators

Paulo Aquino
Ranch Hand

Joined: Apr 29, 2002
Posts: 200

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

Joined: Nov 05, 2002
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.


SCJP1.4<br />SCJD1.4 (preparing)
John Wolf
Ranch Hand

Joined: Feb 18, 2002
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


SCJP 1.2, SCJP 1.4, SCJA, SCWCD 1.4<br /> <br />------------------------------<br />
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Shifting operators