将字节数组值以little endian顺序转换为short值

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

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

转换为短值时会导致:

259,208,241,292

Java中有一种简单的方法可以将字节值转换为相应的短值吗? 我可以编写一个循环,它只占用每个高字节并将其移位8位,并将其与低字节一起使用,但这会影响性能。

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