Behaviour of unsigned right shift applied to byte variable

前端 未结 6 626
星月不相逢
星月不相逢 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:26

    According to Bitwise and Bit Shift Operators:

    The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.

    So with b >> 4 you transform 1111 0001 to 1111 1111 (b is negative, so it appends 1) which is 0xff.

提交回复
热议问题