4

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
randomcompiler
  • 309
  • 2
  • 14
  • 1
    easy google search can give you the answer. – MoonBun Nov 06 '14 at 16:49
  • 1
    Q: "Why does language X do Y the way it does?" A: Because the spec says so. – Durandal Nov 06 '14 at 16:56
  • Well common sense came in the way so I din't think of checking spec, which said: (16>>1) 32 times would fetch the same result as (16>>32) just once. – randomcompiler Nov 06 '14 at 18:04
  • This is a reasonable question. In fact, I think it's a good question, and useful Q&A reference material for SO. In any case, this is ***by no reasonable means whatsoever*** a duplicate of a question that just asks in general how shift operators work, and not one of the answers to the linked question comes even close to explaining this behavior. The answer given here, however, explains this perfectly. – Adi Inbar Nov 07 '14 at 04:18

1 Answers1

10

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • Great response ! Thank you so much. – randomcompiler Nov 06 '14 at 18:00
  • If your question has been answered, please [mark the answer that you feel best addressed your question as accepted](http://stackoverflow.com/help/someone-answers), rather than posting a comment thanking the answerer. Once you have at least 15 rep, you can also [upvote](http://stackoverflow.com/help/why-vote) the accepted answer and any other answers you found useful. – Adi Inbar Nov 07 '14 at 04:19