1

I found this solution for converting a byte to a char on StackOverflow:

byte b = 65;
char c = (char)(b & 0xFF);

What i don't get is the bitwise and with 0xFF. How is the above different from this one?

byte b = 65;
char c = (char)b;

Can someone explain to me step by step what gets converted to what type?

Luca Fülbier
  • 2,641
  • 1
  • 26
  • 43

1 Answers1

1

"& 0xff" is typically used in Java to cut off the sign extension for implicit conversions from bytes to larger integer types.

In Java, byte is a signed data type, where values are stored using two's complement, so -1 is represented as 0xff. The corresponding int representation of -1 is 0xffffffff. Thus, when converting from a byte to an integer, all additional leading bits are filled from the highest bit of the byte.

The bitwise and is not needed for byte values up to 0x7f. But if you want to convert a e.g. a non-breaking space (code point 160 / 0xa0), it would get sign extended to 0xffa0, which is a different character than the intended char value of 0x00a0.

Stefan Haustein
  • 18,427
  • 3
  • 36
  • 51