Behaviour of unsigned right shift applied to byte variable

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

    byte b=(byte) 0xf1;

    if (b<0)

    d = (byte) ((byte) ((byte)(b>>1)&(byte)(0x7F)) >>>3);

    else

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

    First, check the value: If the value is negative. Make one right shift, then & 0x7F, It will be changed to positive. then you can make the rest of right shift (4-1=3) easily.

    If the value is positive, make all right shift with >>4 or >>>4. It does'nt make no difference in result nor any problem of right shift.

提交回复
热议问题