Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

bit-shifting: int >>> 32

 
Juergen Rubow
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For an explanation of this and other "gotchas" in Java, take a look at Roedy Green's List of Java Gotchas.
 
Juergen Rubow
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks,
very informative!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic