Behaviour of unsigned right shift applied to byte variable

Viewed 11190

Consider the following snip of java code

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

output:

c=0xff
d=0xff

expected output:

c=0x0f

how? as b in binary 1111 0001 after unsigned right shift 0000 1111 hence 0x0f but why is it 0xff how?

6 Answers

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).

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.

Related