In java, why can a byte type use & 0xff to perform an operation without right shifting?

I know that in Java, the byte type will first be converted to int before performing the right shift operation.

So in Java we will get the wrong answer for a byte type operation ->>

For example,

byte b=(byte)0xf1;
byte c=(byte)(b>>4);
byte d=(byte)(b>>>4);
byte e=(byte)((b&0xff)>>4);

      

d corresponds to c. but e anser is correct. I can't think of a reason.

thank

+3


source to share


3 answers


As said, Java always evaluates with int

or more, so

Consider b = 1111 0001

(note the top bit is set, so b

it's actually -15)

implicit casting to int:
(int)b = 1111 .... 1111 0001

do the right shift:
(b>>4) = 1111 1111 .... 1111 1111


(b>>>4) = 0000 1111 .... 1111 1111

an explicit cast to bool: c = d = 1111 1111

.




consider e=(byte)((b&0xff)>>4);

implicit casting to int:
(int)b = 1111 .... .... 1111 0001

And with 0xff:
x&0xff = 0000 .... 0000 1111 0001

do the right shift:
(b&0xff)>>4 = 0000 .... 0000 1111

explicit conversion to byte:
e = 0000 1111

+1


source


The smallest type in java is int. This is partly because CPUs currently operate on integer or large types. As a result, the JVM was implemented based on int and other smaller datatypes like byte, char, boolean were added just for convenience.



So, when you do bit operations, you can use mismatches as you mentioned.

0


source


You yourself answered your own question: "before performing the right shift operation, first convert to int", so

byte e=(byte)((b&0xff)>>4);

      

Firstly

b -> int => 0xfffffff1 

      

then

0xfffffff1 & 0xff => 0xf1 

      

then

0xf1 >> 4 => 0xf

      

0


source