This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes bit-shifting: int  >>> 32 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "bit-shifting: int  >>> 32" Watch "bit-shifting: int  >>> 32" New topic
Author

bit-shifting: int >>> 32

Juergen Rubow
Greenhorn

Joined: Aug 18, 2002
Posts: 2
Hi folks,
can someone explain why
int i = -1;
System.out.println(i >>> 32);
prints -1 and not 0 as I expected.
So ((i >>> 31) >>> 1) is not equal to (i >>> 32)?
greetings Juergen.
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
This is one of the most confusing and counter-intuitive things people seem to encounter when first learning Java.
If i is an integer, the compiler treats i>>>j as i>>>(j % 32), so i>>>32 is equivalent to i>>>0 which is equivalent to just plain i.
The same rule is true for >> and << .
The only explanation I've seen is that this optimizes the use of certain CPUs.


Ron Newman - SCJP 1.2 (100%, 7 August 2002)
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
For an explanation of this and other "gotchas" in Java, take a look at Roedy Green's List of Java Gotchas.


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Juergen Rubow
Greenhorn

Joined: Aug 18, 2002
Posts: 2
Thanks,
very informative!
 
 
subject: bit-shifting: int >>> 32