Converting byte array values in little endian order to short values

孤街醉人 提交于 2019-11-27 03:15:35

问题


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.


回答1:


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... */
}



回答2:


 /* 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;
 }


来源:https://stackoverflow.com/questions/14827398/converting-byte-array-values-in-little-endian-order-to-short-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!