How can I assign 2 bytes to a variable in Java? I know I can do this:
byte val = 2; // this is one byte with 0000 0010
But I need to assign 2 bytes to val. How can I do this?
解决方案
As well as using an array of two bytes, you can use a short, which is guaranteed by the Java language spec to be 16 bits wide.
short x = 0x1234s; // assigns 0x34 to the lower byte, 0x12 to the higher byte.
If you have two bytes that you want to combine into a short, you'll need
shift the higher byte by 8 bits and combine them with bitwise or:
byte b1 = 0x12;
byte b2 = 0x34;
short x = ((short)b1 << 8) | b2;
If you want to assign different bits to a single byte variable, then you do that with the right-shift and bitwise or operators as well. Bit n is identified by (1<
byte b = (1<<3)|(1<<2); // b is set to 0000 1100