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?
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?
Are you looking for a byte array of length 2? In this case:
byte[] val = new byte[2];
val[0] = 2;
val[1] = something else;
Are you talking about assigning 2 bytes or 2 bits?
byte b = 5; //0000 0101
You may also want to try http://java.sun.com/j2se/1.4.2/docs/api/java/util/BitSet.html
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<<n). 0 is the first bit of the byte, 7 the last. So setting two bits is done like:
byte b = (1<<3)|(1<<2); // b is set to 0000 1100
You can store two values in one field using XOR :)
byte a, b, c;
a = 5;
b = 16;
c = a ^ b;
...
byte temp_a, temp_b;
temp_a = c ^ 16; /* temp_a == 5 */
temp_b = c ^ 5; /* temp_b == 16 */
As you might have noticed, you need one of the original values to retrieve the other, so this technique is not as ... useful as the bit-shift method suggested.
You might want to take a look at Javolution's Struct class. http://javolution.org/target/site/apidocs/javolution/io/Struct.html
It lets you lay out structures with fixed length members and specific memory alignments. The implementation is backed by a ByteBuffer, so you can allocate it using direct memory if you are interacting with native code.