Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why -1 >> 1 = -1 ?

 
Daniel Liu
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could some some explain me why -1 >> 1 = -1 ?
 
Ankur Gupta
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because >> operator propagates the sign, while >>> adds zeros to the most significant bits whatever may be the sign.
Ankur
 
Daniel Liu
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Would you please explain more what the word "propagate" means?
Originally posted by Ankur:
Because >> operator propagates the sign, while >>> adds zeros to the most significant bits whatever may be the sign.
Ankur

 
Ankur Gupta
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It means that >> operator will put the same sign in the most significant bits i.e. for +ve nos. it will put zeros and for -ve nos it will put 1 in the most significant bits.
 
Daniel Liu
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. That is what i do't know.
Originally posted by Ankur:
It means that >> operator will put the same sign in the most significant bits i.e. for +ve nos. it will put zeros and for -ve nos it will put 1 in the most significant bits.

 
ricky gonzalez
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I still don't understand. -1 is 11111111111111111111111111111111 (32 1's)in binary. Shifting one position to the left gives 1111111111111111111111111111111 (31 1's). How can the value stay at -1?
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please check the following code:
class Test
{
public static void main(String[] args)
{
int a=-1;
System.out.println(Integer.toBinaryString(a));
a=a>>1;
System.out.println(Integer.toBinaryString(a));
a=a>>>1;
System.out.println(Integer.toBinaryString(a));


}
}
OUTPUT:
a)32 1's(for a=-1)
b)32 1's(for a=a>>1)
c)31 1's(for a=a>>>1)
At b,though the right side is shifted by one bit,the left hand side is always filled with the value of the most significant bit
(here in this case it is one for -1 in binary).Whereas at c,the left side is filled with zero and not by the value of most significant bit(which is still one ).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic