aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why -1 >> 1 = -1 ? 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 "why -1 >> 1 = -1 ?" Watch "why -1 >> 1 = -1 ?" New topic
Author

why -1 >> 1 = -1 ?

Daniel Liu
Greenhorn

Joined: Jul 05, 2000
Posts: 19
Could some some explain me why -1 >> 1 = -1 ?

Daniel
Ankur Gupta
Ranch Hand

Joined: Jun 13, 2000
Posts: 66
Because >> operator propagates the sign, while >>> adds zeros to the most significant bits whatever may be the sign.
Ankur
Daniel Liu
Greenhorn

Joined: Jul 05, 2000
Posts: 19
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

Joined: Jun 13, 2000
Posts: 66
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

Joined: Jul 05, 2000
Posts: 19
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

Joined: Jun 30, 2000
Posts: 167
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

Joined: Nov 22, 2008
Posts: 18944
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 ).
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: why -1 >> 1 = -1 ?