为什么右移(>>)位操作超过字节会产生奇怪的结果?

ste*_*emm 2 java math bit bitwise-operators

有一个字节[01100111],我要以这种方式打破它,[0|11|00111] 所以在将这个字节的部分移动到不同的字节后,我会得到:

[00000000] => 0 (in decimal)
[00000011] => 3 (in decimal)
[00000111] => 7 (in decimal)
Run Code Online (Sandbox Code Playgroud)

我试着用这样的代码做到这一点:

byte b=(byte)0x67;
byte b1=(byte)(first>>7);
byte b2=(byte)((byte)(first<<1)>>6);        
byte b3=(byte)((byte)(first<<3)>>3);
Run Code Online (Sandbox Code Playgroud)

但我得到了:

b1 is 0
b2 is -1 //but I need 3....
b3 is 7
Run Code Online (Sandbox Code Playgroud)

我错了哪里?

谢谢

Oli*_*rth 8

您的结果会自动进行签名.

尝试屏蔽和移动而不是双移,即:

byte b1=(byte)(first>>7) & 0x01;
byte b2=(byte)(first>>5) & 0x03;
byte b3=(byte)(first>>0) & 0x1F;
Run Code Online (Sandbox Code Playgroud)