问题
I want to create a byte using an integer. For example I have an integer of 4, I want to create a byte with a value of 4. When I do something like
byte test = 134;
I get an byte value of -122 wheras I want a byte value of simply 134 so that i can convert this to ascii later on.
I am unsure of how to achieve this but would welcome any help that can be provided. Thanks.
回答1:
In Java byte
s are interpreted as signed (along with int
s, short
s, and long
s). The unsigned byte value of 134
is bit-equivalent to the signed byte value of -122
. If you wish to use the unsigned value of a byte
, you can do so by storing this value in a signed integer with more than 8 bits, such as an int
:
byte test = (byte) 134;
int unsignedByteValue = ((int) test) & 0xff;
// now unsignedByteValue == 134
The bitmask of 0xff
ensures that only the lower 8 bits of unsignedByteValue
are ones. Otherwise, a negative signed byte
would result in a negative signed int
by sign extension.
回答2:
In Java, all bytes are signed. They have a value from -128 to 127. If you print out the byte, that's all you will get.
But Java has a different type for characters. You should use this instead:
char test = 134;
The char
type is unsigned and will accommodate characters with numeric values up to 65,535.
来源:https://stackoverflow.com/questions/21246786/creating-a-byte-from-an-integer