public void int2byte(){
int x = 128;
byte y = (byte) x;
System.out.println(Integer.toHexString(y));
}
I got result ffffff80, why not 80? I got result 7f when x = 127.
public void int2byte(){
int x = 128;
byte y = (byte) x;
System.out.println(Integer.toHexString(y));
}
I got result ffffff80, why not 80? I got result 7f when x = 127.
Bytes are signed in Java. When you cast 128
to a byte
, it becomes -128
.
The int
128
: 00000000 00000000 00000000 10000000
The byte
-128
: 10000000
Then, when you widen it back to an int
with Integer.toHexString
, because it's now negative, it gets sign-extended. This means that a bunch of 1
bits show up, explaining your extra f
characters in the hex output.
You can convert it in an unsigned fashion using Byte.toUnsignedInt
to prevent the sign extension.
Converts the argument to an
int
by an unsigned conversion. In an unsigned conversion to anint
, the high-order 24 bits of theint
are zero and the low-order 8 bits are equal to the bits of thebyte
argument.
System.out.println(Integer.toHexString(Byte.toUnsignedInt(y)));
An alternative is to bit-mask out the sign-extended bits by manually keeping only the 8 bits of the byte
:
System.out.println(Integer.toHexString(y & 0xFF));
Either way, the output is:
80
This is because a positive value of 128 cannot be represented with a signed byte
The range is -128 to 127
So your int becomes sign-extended so instead of 0x00000080 you get 0xffffff80
Edit: As others have explained:
Integer 128 shares the last 8 bits with the byte (-128)
The difference is that Integer 128 has leading zeros.
0x00000080 (0000 0000 0000 0000 0000 0000 1000 0000)
while the byte -128 is just
0x80 (1000 0000)
When you convert byte -128 using Integer.toHexString()
it takes the leading 1 and sign-extends it so you get
0xffffff80 (1111 1111 1111 1111 1111 1111 1000 0000)