Behaviour of unsigned right shift applied to byte variable

前端 未结 6 630
星月不相逢
星月不相逢 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条回答
  •  猫巷女王i
    2020-11-30 08:03

    The problem is that all arguments are first promoted to int before the shift operation takes place:

    byte b = (byte) 0xf1;
    

    b is signed, so its value is -15.

    byte c = (byte) (b >> 4);
    

    b is first sign-extended to the integer -15 = 0xfffffff1, then shifted right to 0xffffffff and truncated to 0xff by the cast to byte.

    byte d = (byte) (b >>> 4);
    

    b is first sign-extended to the integer -15 = 0xfffffff1, then shifted right to 0x0fffffff and truncated to 0xff by the cast to byte.

    You can do (b & 0xff) >>> 4 to get the desired effect.

提交回复
热议问题