Signed versus unsigned values

2024-09-27, by Frank Delporte

When using bits and bytes to control electronic components, the conversion from a byte to, e.g., logging output can be a bit confusing as Java uses signed values. This means a byte value has a range of -128 till 127, while you would expect 0 (0x00) till 255 (0xFF).

For example, the hex value 0x8F (10001111) is handled like this:

var b = (byte) Integer.parseInt("10001111", 2);
System.out.println("Byte value 10001111: " + b);

// Output
Byte value 10001111: -113

You can use Byte.toUnsignedInt(b) to get the expected, unsigned value:

var unsignedInt = Byte.toUnsignedInt(b);
System.out.println("Byte to unsigned integer: " + unsignedInt);

// Output
Byte to unsigned integer: 143

This gets explained more in detail in this blog post and this video: