I have an integer called writePos
that takes a value between [0,1023]
. I need to store it in the last two bytes of a byte array called bucket
. So, I figure I need to represent it as a concatenation of the array's last two bytes.
How would I go about breaking down writePos
into two bytes that, when concatenated and cast into an int
, produces writePos
again?
How would I go about concatenating once I get it broken down into the bytes?
This would be covered high-level by a ByteBuffer.
short loc = (short) writeLocation;
byte[] bucket = ...
int idex = bucket.length - 2;
ByteBuffer buf = ByteBuffer.wrap(bucket);
buf.order(ByteOrder.LITTLE__ENDIAN); // Optional
buf.putShort(index, loc);
writeLocation = buf.getShort(index);
The order can be specified, or left to the default (BIG_ENDIAN).
index
.putShort
writes to the byte array, modifying two bytes, a short.getShort
reads a short from the byte array, which can be put in an int.Explanation
A short
in java is a two-byte (signed) integral number. And that is what is meant. The order is whether LITTLE_ENDIAN: least significant byte first (n % 256, n / 256) or big endian.