Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in Java right-shifting 16 by 32 results in 16 and not 0? 16>>32 = 16 Why? [duplicate]

Tags:

java

I came across a weird looking situation while using right-shift operator in java. When I right-shift 16 by 31 it results in 0 however on trying to right-shifting 16 by 32 it remains 16 itself. Could someone please explain it as I am going crazy over it.

public class RightShiftTest {

    public static void main(String args[])  {        
        int b = 16;
        System.out.println("Bit pattern for int " + b + " is " +Integer.toBinaryString(b));

        // As expected it is 0 
        System.out.println("After right-shifting " + b + " for 31 times the value is " + (b>>31) + " and bit pattern is " +Integer.toBinaryString(b>>31));

        // But why is it not 0 but 16
        System.out.println("After right-shifting " + b + " for 32 times the value is " + (b>>32) + " and bit pattern is " +Integer.toBinaryString(b>>32));
     }    
}

Output:
Bit pattern for int 16 is 10000
After right-shifting 16 for 31 times the value is 0 and bit pattern is 0
After right-shifting 16 for 32 times the value is 16 and bit pattern is 10000
like image 512
randomcompiler Avatar asked Dec 25 '22 02:12

randomcompiler


1 Answers

The Java Language Specification states

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.

The value 32 is represented as

100000

the lowest 5 bits are 00000 so 0, shifted by 0 bits.

like image 85
Sotirios Delimanolis Avatar answered Dec 28 '22 09:12

Sotirios Delimanolis