Convert unsigned byte to signed byte

Joeblackdev picture Joeblackdev · Aug 6, 2011 · Viewed 35.2k times · Source

Is there an easy and elegant way to convert an unsigned byte value to a signed byte value in java? For example, if all I have is the int value 240 (in binary (24 bits + 11110000) = 32bits), how can I get the signed value for this int?

Answer

ostefano picture ostefano · Aug 6, 2011

In Java all the primitive types, except for char, are signed. You can't have an unsigned byte. The only thing you may do is to cast the unsigned byte to an int so you can read its proper value:

int a = b & 0xff

If you want to store an unsigned byte value in a byte type, you obviously can, but every time you need to "process" it, just remember to cast it again as showed above.