Why is my Java short getting filled with 1s with an unsigned right shift?

bushidocodes :

When I execute an unsigned right shift as follows:

short value = (short)0b1111111111100000;
System.out.println(wordToString(value));
value >>>= 5;

I get 1111111111111111. So, the value is shifted right, but filled with 1s, which seems to be the same behavior as >>

However, I was expecting it to fill with 0s regardless of sign, yielding the following: 0000011111111111

Here is a relevant REPL to play with my code: https://repl.it/@spmcbride1201/shift-rotate

gscaparrotti :

The behaviour you're getting has to do with the fact that shorts are promoted to ints before applying the shift operation. In fact, if you assign the result of the shift operator to a int variable you get the expected result:

  public static void main(String[] args) {

    short value = (short)0b1111111111100000;
    System.out.println(value); //-32, which is the given number
    int result = value >>> 5;
    System.out.println(result); //134217727, which is 00000111111111111111111111111111

  }

If you assign the result to a short, you only get the lower bits.

This is due to the fact that the bytecode language doesn't really deal with any types smaller than int.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=4294&siteId=1