Search code examples
javaarraystype-conversionbytebucket

How can I concatenate two bytes in java?


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.

  1. How would I go about breaking down writePos into two bytes that, when concatenated and cast into an int, produces writePos again?

  2. How would I go about concatenating once I get it broken down into the bytes?


Solution

  • 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).

    1. The ByteBuffer wraps the original byte array, and changes to ByteBuffer effect on the byte array too.
    2. One can use sequential writing and reading an positioning (seek), but here I use overloaded methods for immediate positioning with index.
    3. putShort writes to the byte array, modifying two bytes, a short.
    4. 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.