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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…