Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert unsigned byte to signed byte

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?

like image 798
Joeblackdev Avatar asked Aug 06 '11 11:08

Joeblackdev


2 Answers

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.

like image 173
ostefano Avatar answered Oct 12 '22 19:10

ostefano


Java does not have unsigned values, except for char. Consider this snippet:

byte val = (byte)255;
System.out.println(String.valueOf(val));

The result will be -1, because the lowest 8 bits got copied over to the byte variable.

like image 32
Tassos Bassoukos Avatar answered Oct 12 '22 18:10

Tassos Bassoukos