Dipu
Dipu

Reputation: 113

Shifted by negative number in java

I have problem with shift operator in Java.I have used following code and not unable to understand how this program generates this output.So please guide me how this program generates this output.

public class Operator {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int s = 8;
        s = s >>-63;
        System.out.println("value of i=" + s);
    }

}

Output: value of i=4

Upvotes: 6

Views: 10201

Answers (5)

Prometheus
Prometheus

Reputation: 35

Shifting with -63 actually shifts with -63 & 0x1f == 1 for int or -63 & 0x3f == 1 for long, because in Java shifting left with >> uses sign-extension, and 1 will shift out any zero bits in the case of 8.

Upvotes: 1

Bruce Zu
Bruce Zu

Reputation: 507

    int s=8;        
    Assert.assertEquals(s >>-63, s >>-63 % 32);
    Assert.assertEquals(s >>-63, s >>-31);
    Assert.assertEquals(s >>-31, s >>32 -31);
    Assert.assertEquals(s >>32 -31,s >>1); 
    Assert.assertEquals(s >>1,s /2); 
    Assert.assertEquals(s/2,4); 

Upvotes: 1

npenkov
npenkov

Reputation: 131

The following 2 statements are producing one and the same result for integers if you want to replace negative shift:

r << -shift

and

r << ((32 - shift) % 32)

(32 is the size of integer in Java)

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499900

From the JLS, section 15.19 (Shift Operators):

If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (§15.22.1) with the mask value 0x1f (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

Now -63 & 0x1f == 1, So this is actually a shift by 1 to the right, hence the answer of 4.

Upvotes: 21

MByD
MByD

Reputation: 137282

s = s >>-63; is like s = s >> 1; (-63 % 32)

Take a look at the shift operator behavior at the JLS §15.19.

Upvotes: 6

Related Questions