将字节数组值(按小字节序顺序)转换为短值

2022-09-01 18:18:37

我有一个字节数组,其中数组中的数据实际上是短数据。字节以小端序排序:

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

当转换为短值时,会导致:

259, 208, 241, 292

在Java中是否有一种简单的方法可以将字节值转换为其相应的短值?我可以编写一个循环,只获取每个高字节并将其移位8位,然后用其低字节或它,但这会影响性能。


答案 1

使用java.nio.ByteBuffer,您可以指定所需的字节序:order()

ByteBuffer有方法将数据提取为byte,char,getShort()getInt(),long,double...

以下是如何使用它的示例:

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