以小端顺序将字节数组值转换为短值 [英] Converting byte array values in little endian order to short values
问题描述
我有一个字节数组,其中数组中的数据实际上是短数据.字节按小端排序:
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
3, 1, -48, 0, -15, 0, 36, 1
转换为短值时会导致:
259、208、241、292
259, 208, 241, 292
Java 中是否有一种简单的方法可以将字节值转换为相应的短值?我可以编写一个循环,只取每个高字节并将其移位 8 位,然后将其与其低字节进行或运算,但这会影响性能.
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.
推荐答案
With java.nio.ByteBuffer 你可以指定你想要的字节序:order().
With java.nio.ByteBuffer you may specify the endianness you want: order().
ByteBuffer 有将数据提取为字节、字符的方法,getShort(), getInt(),长,双...
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... */
}
这篇关于以小端顺序将字节数组值转换为短值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!