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

时间:2011-04-11 15:35:41

标签: java math bit bitwise-operators

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

[00000000] => 0 (in decimal)
[00000011] => 3 (in decimal)
[00000111] => 7 (in decimal)

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

byte b=(byte)0x67;
byte b1=(byte)(first>>7);
byte b2=(byte)((byte)(first<<1)>>6);        
byte b3=(byte)((byte)(first<<3)>>3);

但我得到了:

b1 is 0
b2 is -1 //but I need 3....
b3 is 7

我错了?

由于

1 个答案:

答案 0 :(得分:8)

您的搜索结果会自动sign-extended

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

byte b1=(byte)(first>>7) & 0x01;
byte b2=(byte)(first>>5) & 0x03;
byte b3=(byte)(first>>0) & 0x1F;
相关问题