Bitwise AND operation with signed byte

Here is the code:

int i = 200;
byte b = (byte) 200;
System.out.println(b);
System.out.println((short) (b));
System.out.println((b & 0xff));
System.out.println((short) (b & 0xff));

      

Here's the result:

-56
-56
200
200

      

The bitwise AND with 0xff shouldn't change anything in b

, but it seems to have an effect, why?

+3


source to share


3 answers


It has the effect, because it 200

is beyond the maximum possible (signed) byte

, 127

. This value has already been assigned -56

due to this overflow. The most significant byte is set -128

.

11001000

      

The first two output operators also show -56

because of this the fact that the cast to short

will perform sign expansion to preserve negative values.

When you do & 0xff

, 2 things happen. First, the value is incremented to int

with sign expansion.

11111111 11111111 11111111 11001000

      



Then bit and is executed, keeping only the last 8 bits. Here the eighth bit is no longer -128

a 128

, so it is 200

restored.

00000000 00000000 00000000 11001000

      

This happens regardless of whether a value is selected for short

or not; a short

is 16 bits and can easily represent 200

.

00000000 11001000

      

+8


source


Java byte

is a signed type. This is why you see a negative number when you print: 200, or 0xC8

, is above the largest positive number represented byte

, so it is interpreted as negative byte

.

However, the constant 0xff

is int

. When you perform arithmetic and bitwise logical operations on byte

and int

* the result becomes int

. This is why you see 200

printed in the second set of examples: (b & 0xff)

creates an integer 200

that remains 200

after reducing the conversion to short

because it 200

fits in short

without becoming negative.



* or another byte

, for that matter; The Java standard specifies a list of conversions that apply depending on the types of the operands.

+1


source


Working with different integer types is a mine field.

for example, what's going on here?

byte b = (byte) 200;

      

it is actually equivalent to

int i = 200;
byte b = (byte)i;

      

while the narrowing cast (byte)

simply takes the lower 8 bits of the value int

.

0


source







All Articles