Friday, February 19, 2010

Unsigned Java Primitives

This one's just a quick note about unsigned primitives and how to work with them in Java, which technically has no notion of 'unsigned'.

If you need to find the unsigned value of a primitive (e.g. you are porting code in another language, or dealing with byte-level networking), you basically need to promote it to the next higher data type, and mask out the bits you don't need (anything above the size of your unsigned data type).


To find the unsigned value of a byte (8 bits):

byte b = ...;
short unsignedB = (0x00FF & ((short)b));

And for a short (16 bits):

short s = ...;
int unsignedShort = (0x0000FFFF & ((int)s));

And so on.

You can read more on this and other exciting topics such as *-endian byte ordering, and why Java doesn't have unsigned in the first place here:

(hint: Gosling didn't think Java developers could understand them!)