Home >Java >javaTutorial >Why Does Java's Int-to-Byte Conversion Result in a Negative Value?

Why Does Java's Int-to-Byte Conversion Result in a Negative Value?

Linda Hamilton
Linda HamiltonOriginal
2024-11-08 13:35:02213browse

Why Does Java's Int-to-Byte Conversion Result in a Negative Value?

Unexpected Behavior in Java Int-to-Byte Conversion

When converting an integer (int) to a byte (byte) in Java, unexpected results may arise. Consider the following code:

int i = 132;

byte b = (byte) i;
System.out.println(b);

Surprisingly, the output is not 132 but rather -124. To understand why, we need to delve into the internal representation of primitive types in Java.

Signed Numbers and Two's Complement

In Java, ints are 32-bit signed integers, while bytes are 8-bit signed integers. A signed integer can represent both positive and negative values using two's complement notation. In this notation, the leftmost bit (MSB) determines the sign of the number, with 0 indicating positive and 1 indicating negative.

Conversion from Int to Byte

When converting from int to byte, Java retains the sign bit and discards the remaining 24 bits. This means that if the int value was positive, the resulting byte value will also be positive. However, if the int value was negative, as in our example, the resulting byte value will appear negative.

The Two's Complement Inversion

To understand this negative behavior, we need to consider the two's complement inversion process. To represent a negative number, two's complement inverts all the bits and adds 1 to the result. In our case, the int value 132 is 10000100 in binary. Inverting the bits and adding 1 gives us 01111011, which is -124 in decimal notation.

Unsigned Byte Values

In our example, we typically expect the byte value to be unsigned, which would give us a positive value of 132 instead of -124. To obtain the unsigned value from the byte, we can apply a bitmask that removes the sign bit and extracts only the lower 8 bits.

byte signedByte = -124;
int unsignedByte = signedByte & 0xff;

System.out.println("Signed: " + signedByte + " Unsigned: " + unsignedByte);

This will print "Signed: -124 Unsigned: 132", giving us the desired unsigned value.

The above is the detailed content of Why Does Java's Int-to-Byte Conversion Result in a Negative Value?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn