I need an unsigned 8 bit integer in Java, and char seems to be the only thing close to that. Although it's double the size, it's unsigned which makes it practical for what I want to use it for (writing a basic emulator which requires unsigned bytes). The problem is that I've heard other programmers say that one shouldn't use char in that manner and should just use int or so. Is this true, and why so?
Asked
Active
Viewed 2.4k times
3 Answers
5
If you need an unsigned 8 bit integer then use byte
. It's easy to make it unsigned in arithemtic operations (where actually sign matters) as byteValue & 0xFF

Evgeniy Dorofeev
- 133,369
- 30
- 199
- 275
-
Yes I already did something like that but with a "wrapper" object. If you don't mind, can you check what I commented to Wudong? – ZimZim May 29 '13 at 08:50
-
1If you need efficiency it's a bad idea, if efficiency isnt an issue then UnsignedByte class instead of java.lang.Byte is a good idea – Evgeniy Dorofeev May 29 '13 at 08:56
-
Byte in Java is an 8-bit signed integer. It is not unsigned. – Faiz Nov 02 '20 at 02:13
3
It is totally reasonable to use byte
to represent an unsigned 8 bit integer with some minor conversion, or Guava's UnsignedBytes
do the conversion to you.

Duncan Jones
- 67,400
- 29
- 193
- 254

Wudong
- 2,320
- 2
- 32
- 46
-
Yes, I thought something like that would be a good solution. I created a "wrapper" which has a byte field and basically interprets negative values as 256 + value (i.e. 236 would be saved as -20 in the byte, and then interpreted as -20 && 256, i.e. 236). I thought that would be okay, but doesn't this cause a lot of overhead, especially because one is creating a new Object that, even if it was empty, would still use 8 bytes? This would normally not be a problem, but I'm messing around with emulation and I assume that emulators need to be as efficient as possible. – ZimZim May 29 '13 at 08:46
3
In Java:
long: [-2^63 , 2^63 - 1]
int: [-2^31 , 2^31 - 1]
short: [-2^15 , 2^15 - 1]
byte: [-2^7 , 2^7 - 1]
char: [0 , 2^16 - 1]
You want an unsigned 8 bit integer means you want a value between [0, 2^8 - 1]. It is clearly to choose short/int/long/char.
Although char can be treated as an unsigned integer, I think It's a bad coding style to use char for anything but characters.
For example,
public class Test {
public static void main(String[] args) {
char a = 3;
char b = 10;
char c = (char) (a - b);
System.out.println((int) c); // Prints 65529
System.out.println((short) c); // Prints -7
short d = -7;
System.out.println((int) d); // Prints -7, Please notice the difference with char
}
}
It is better to use short/int/long with conversion.

Le Wang
- 76
- 2