Unsigned byte in Java
Java does not have unsigned data types. Your options are:
- Use a wider datatype such as
short
,char
orint
- Use a
byte
and “manually” interpret it as unsigned (described below)
An unsigned byte
A byte
is always signed in Java, but nothing prevents you from viewing a byte
simply as 8 bits and interpret those bits as a value between 0 and 255.
Java byte value | Bits | Interpreted as unsigned |
---|---|---|
0 | 00000000 |
0 |
1 | 00000001 |
1 |
⋮ | ⋮ | ⋮ |
127 | 01111111 |
127 |
−128 | 10000000 |
128 |
⋮ | ⋮ | ⋮ |
−2 | 11111110 |
254 |
−1 | 11111111 |
255 |
Keep in mind that there’s nothing you can do to force your interpretation upon someone else’s method. If a method accepts a byte
, then that method accepts a value between −128 and 127 unless explicitly stated otherwise.
Here are a couple of useful conversions / manipulations.
Printing an unsigned byte
Use Byte.toUnsignedInt
and print the resulting int
:
byte b = (byte) 0b10010110; // -106 signed, or 150 unsigned
System.out.println("Value of my unsigned byte: " + Byte.toUnsignedInt(b)); // 150
Converting from int
to unsigned byte
Casting to byte
throws away all but the lowest 8 bits.
int i = 150; // 00000000 00000000 00000000 10010110
byte b = (byte) i; // 10010110
System.out.println(b); // -106
System.out.println(Byte.toUnsignedInt(b)); // 150
Converting from unsigned byte
to int
Use Byte.toUnsignedInt
to avoid sign extension.
byte b = (byte) 0b10010110; // -106 or 150
int signed = b; // -106 (with sign extension)
int unsigned = Byte.toUnsignedInt(b); // 150 (without sign extension)
Or, equivalently:
int unsigned = b & 0xff;
Parsing an unsigned byte
byte b = (byte) Integer.parseInt("150");
System.out.println(Byte.toUnsignedInt(b)); // 150
Or, using Guava:
byte b = UnsignedBytes.parseUnsignedByte("150");
Compare unsigned byte
s
Convert to int
and compare.
int cmp = Integer.compare(Byte.toUnsignedInt(b1), Byte.toUnsignedInt(b2))
// cmp = -1 => b1 < b2
// cmp = 0 => b1 = b2
// cmp = 1 => b1 > b2
Or, using Guava
int cmp = UnsignedBytes.compare(b1, b2);
Arithmetics
The 2-complement representation “just works” for addition, subtraction and multiplication.
// two unsigned bytes
byte b1 = (byte) 200;
byte b2 = (byte) 15;
byte sum = (byte) (b1 + b2); // 215
byte diff = (byte) (b1 - b2); // 185
byte prod = (byte) (b2 * b2); // 225
Division requires conversion of operands, and then convertion of result back to byte
.
byte ratio = (byte) (Byte.toUnsignedInt(b1) / Byte.toUnsignedInt(b2));