Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shifted by negative number in java

Tags:

java

bit-shift

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

like image 398
Dipu Avatar asked Nov 28 '22 17:11

Dipu


1 Answers

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.

like image 101
Jon Skeet Avatar answered Dec 04 '22 21:12

Jon Skeet