Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# why -1 >> 1 = -1 ?

Daniel Liu
Greenhorn
Posts: 19
Could some some explain me why -1 >> 1 = -1 ?

Ankur Gupta
Ranch Hand
Posts: 66
Because >> operator propagates the sign, while >>> adds zeros to the most significant bits whatever may be the sign.
Ankur

Daniel Liu
Greenhorn
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
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
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
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
Posts: 18944
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 ).