Search code examples
javaarraysbyteendianness

Converting byte array values in little endian order to short values


I have a byte array where the data in the array is actually short data. The bytes are ordered in little endian:

3, 1, -48, 0, -15, 0, 36, 1

Which when converted to short values results in:

259, 208, 241, 292

Is there a simple way in Java to convert the byte values to their corresponding short values? I can write a loop that just takes every high byte and shift it by 8 bits and OR it with its low byte, but that has a performance hit.


Solution

  • With java.nio.ByteBuffer you may specify the endianness you want: order().

    ByteBuffer have methods to extract data as byte, char, getShort(), getInt(), long, double...

    Here's an example how to use it:

    ByteBuffer bb = ByteBuffer.wrap(byteArray);
    bb.order( ByteOrder.LITTLE_ENDIAN);
    while( bb.hasRemaining()) {
       short v = bb.getShort();
       /* Do something with v... */
    }