问题
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?
回答1:
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.
回答2:
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.
回答3:
public int getUnsignedByte(byte[] bytes, int offset) {
return (bytes[offset] & 0xFF);
}
should do the work.
回答4:
Here's how to store and convert an unsigned byte value:
byte b = (byte) 144; // binary value = 10010000
If you cast b
to an int
here's what happens:
int i = b;
System.out.println("value: "+i);
System.out.println("binary: " + Integer.toBinaryString(i));
Output:
value: -112 <- Incorrect value
binary: 11111111111111111111111110010000
Why does this happen? Bytes are signed in Java, and b
is negative so the cast operation fills the resulting int with 1s from the left. More on java data formats.
So how do we get back from -112 to the correct value of 144? We need a 32-bit bitmask, which we can create with an int
:
int mask = 0x000000FF; // This is often shortened to just 0xFF
Now we can use the bitwise &
operator to "zero out" the left most 24 bits, leaving only our original 8 bits.
int unsignedValue = b & mask; // value = 144
Our original value of 144 has been restored and can be safely cast back to a byte:
byte original = (byte) unsignedValue;
回答5:
Java only supports signed bytes so whenever you place a value in a byte, its assumed to be signed.
byte b = (byte) 240;
However if you want to store an unsigned byte, you need to handle this yourself. (i.e. Java doesn't support it but you can do it)
For operations like +, -, *, <<, >>>, ==, !=, ~ you don't need to change anything, For operations like <, > you need to have make minor adjustments, and for operations like /, % you need to use a larger data type.
A common alternative is to use a larger data type like int
to store values 0 - 255. There is not much disadvantage in doing so.
来源:https://stackoverflow.com/questions/6966580/convert-unsigned-byte-to-signed-byte