1
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.

Pi Pi
  • 861
  • 3
  • 13
  • 22
  • 3
    Because `toHexString()` requires an `int` parameter, so the *signed* `byte` is widened to `int` using sign-extension. – Andreas Aug 02 '18 at 17:10
  • 2
    127(int) = -128(byte) = -128(int) = 0xffffff80(int) – zhh Aug 02 '18 at 17:13
  • https://stackoverflow.com/questions/44409773/why-have-leading-ffffff-for-single-byte – SOS Aug 02 '18 at 17:14

2 Answers2

3

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 an int, the high-order 24 bits of the int are zero and the low-order 8 bits are equal to the bits of the byte 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
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • Or by playing with shift operators: Shift the 8 bits to the outer left and then shift them unsigned back to the outer right `System.out.println(Integer.toHexString(y << 24 >>> 24)); // 80` – LuCio Aug 02 '18 at 19:15
2

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)
gtgaxiola
  • 9,241
  • 5
  • 42
  • 64
  • Correct, but incomplete. You should show what the actual `byte` value is, i.e. `-128`, and explain why and where the sign-extension occurs. – Andreas Aug 02 '18 at 17:13