# shift operators for negative values

Rosie Nelson

Ranch Hand

Posts: 31

posted 15 years ago

JLS (15.19 Shift Operators) states:-

Question:-

If I want to compute for a negative value of n, i.e -8 >> s what is the procedure... is there a formula that holds true for negative values?

e.g how would I calculate:-

(1) -8 >> 31

(2) -8 >> -3

*The value of n>>s is n right-shifted s bit positions with sign-extension. The resulting value is (n/2^s). For nonnegative values of n, this is equivalent to truncating integer division, as computed by the integer division operator /, by two to the power s.*Question:-

If I want to compute for a negative value of n, i.e -8 >> s what is the procedure... is there a formula that holds true for negative values?

e.g how would I calculate:-

(1) -8 >> 31

(2) -8 >> -3

Andre Zhang

Greenhorn

Posts: 9

Neha Sawant

Ranch Hand

Posts: 204

Valentin Crettaz

Gold Digger

Sheriff

Sheriff

Posts: 7610

posted 15 years ago

OK the first thing to point out is that:

if the left-hand side is an int then the right-hand side is ANDed with 0x1F and if the left-hand side is a long then the right-hand side is ANDed with 0x3F.

Now, let's take a look at 2<<3 and 2<<-3.

2<<3 : No suprises here the result is 16 as expected.

BUT for 2<<-3 the story is different.

the right-hand side (-3) in binary is

11111111 11111111 11111111 11111101

and ANDed with 0x1F it gives

11101 which is in fact 29 (32-3) and the result of the shifting is 1073741824.

To summarize: the right-hand side is in all cases ANDed with 0x1F (or 0x3F) and that result is the one used in the shifting operation. So there is no way to shift more than 31 positions (to the left or to the right) because of that AND operation whatever the sign of the rigth-hand side is.

HIH

------------------

Valentin Crettaz

Sun Certified Programmer for Java 2 Platform

if the left-hand side is an int then the right-hand side is ANDed with 0x1F and if the left-hand side is a long then the right-hand side is ANDed with 0x3F.

Now, let's take a look at 2<<3 and 2<<-3.

2<<3 : No suprises here the result is 16 as expected.

BUT for 2<<-3 the story is different.

the right-hand side (-3) in binary is

11111111 11111111 11111111 11111101

and ANDed with 0x1F it gives

11101 which is in fact 29 (32-3) and the result of the shifting is 1073741824.

To summarize: the right-hand side is in all cases ANDed with 0x1F (or 0x3F) and that result is the one used in the shifting operation. So there is no way to shift more than 31 positions (to the left or to the right) because of that AND operation whatever the sign of the rigth-hand side is.

HIH

------------------

Valentin Crettaz

Sun Certified Programmer for Java 2 Platform

SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML

[Blog] [Blogroll] [My Reviews] My Linked In