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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With