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).

Examples...

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: http://www.darksleep.com/player/JavaAndUnsignedTypes.html

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

9 comments:

Anonymous said...

很棒的分享~~~來留個言囉~~~~ .........................................

Anonymous said...

Unable to give you a heart. so have a reply to push up your post. ........................................

Anonymous said...

婚姻對男人來說是賭他的自由,對女人而言卻是賭她的幸福。 ..................................................

Anonymous said...

I love readding, and thanks for your artical...................................................

Anonymous said...

恨一個人,比原諒一個人,更傷力氣。..................................................

Anonymous said...

上來打聲招呼,祝你一切平安! ........................................

Anonymous said...

Nice post ~ 3Q..............................................................

Anonymous said...

好問才能博學。.............................................

Anonymous said...

不要把生命看得太嚴肅,反正我們不會活著離開。..................................................