Converting byte array values in little endian order to short values

前端 未结 2 1359
南旧
南旧 2020-12-10 01:26

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 conver

相关标签:
2条回答
  • 2020-12-10 01:57

    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... */
    }
    
    0 讨论(0)
  • 2020-12-10 02:00
     /* Try this: */
    public static short byteArrayToShortLE(final byte[] b, final int offset) 
    {
            short value = 0;
            for (int i = 0; i < 2; i++) 
            {
                value |= (b[i + offset] & 0x000000FF) << (i * 8);
            }            
    
            return value;
     }
    
     /* if you prefer... */
     public static int byteArrayToIntLE(final byte[] b, final int offset) 
     {
            int value = 0;
    
            for (int i = 0; i < 4; i++) 
            {
               value |= ((int)b[i + offset] & 0x000000FF) << (i * 8);
            }
    
           return value;
     }
    
    0 讨论(0)
提交回复
热议问题