开发者

Why does right shift (>>) bit operation over byte give strange result?

There is a byte [01100111] and I've to break it in such way [0|11|00111] so after moving parts of this byte into different bytes I'll get:

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

I've try to do that with such code:

byte b=开发者_StackOverflow中文版(byte)0x67;
byte b1=(byte)(first>>7);
byte b2=(byte)((byte)(first<<1)>>6);        
byte b3=(byte)((byte)(first<<3)>>3);

But I got:

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

Where I've mistake?

Thanks


Your results are being automatically sign-extended.

Try masking and shifting instead of double-shifting, i.e.:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜