简体   繁体   中英

What happens when you operate bytes bitwise?

Take a look at this code:

byte a = -124;
System.out.println(a);
System.out.println((a & 0xFF));

It outputs:

-124
132

It's very, very surprising to me. After all, byte contains only 8 bits, so that it shouldn't not be changed after and with 0xFF (ie 11111111 ).

One possible reason is that Java converts byte to int before doing bitwise operation. Is it the case? If so, why?

By default, Java uses the int primitive type for numbers.

If you want to do bitwise operations on integer primitives of types other than int you can cast the operands explicitly:

byte b = -124;
System.out.println("Byte: " + b);
System.out.println("Byte after bitwise and: " + (b & (byte) 0xFF));

The code above produces the following output:

 Byte: -124 Byte after bitwise and: -124 

0xFF is indeed an int type. So 'a' is promoted to an int prior to the operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM