Search code examples
javaandroidarraysshort

Conversion shortarray to bytearray & bytearray to shortarray


I have tried this short2byte and byte2short conversion, works fine but time consuming.

I am converting byte to short as shown below

ByteBuffer.wrap(bData).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(sData);

In same fashion I want to convert back short to byte.

I have searched and seen many examples but did not get it as I want.


Solution

  • I think I got the way.

    conversion byte to short using ByteBuffer

    byte[] bData= {};
    short[] sData= new short[bData.length/2];
    // to turn bytes to shorts as either big endian or little endian. 
    ByteBuffer.wrap(bData).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(sData);
    

    conversion short to byte using ByteBuffer

    // to turn shorts back to bytes.
    byte[] bData= new byte[sData.length * 2];
    ByteBuffer.wrap(bData).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(sData);