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


there byte [01100111] , i've break in such way [0|11|00111] after moving parts of byte different bytes i'll get:

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

i've try such code:

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

but got:

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

where i've mistake?

thanks

your results being automatically sign-extended.

try masking , 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; 

Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -