Behaviour of unsigned right shift applied to byte variable

前端 未结 6 628
星月不相逢
星月不相逢 2020-11-30 07:46

Consider the following snip of java code

byte b=(byte) 0xf1;
byte c=(byte)(b>>4);
byte d=(byte) (b>>>4);

output:

<         


        
6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 08:06

    The byte operand is promoted to an int before the shift.

    See https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.19

    Unary numeric promotion (§5.6.1) is performed on each operand separately. (Binary numeric promotion (§5.6.2) is not performed on the operands.)

    And https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.1

    Otherwise, if the operand is of compile-time type byte, short, or char, it is promoted to a value of type int by a widening primitive conversion (§5.1.2).

提交回复
热议问题