在小端以短值转换字节数组值 [英] Converting byte array values in little endian order to short values

查看:206
本文介绍了在小端以短值转换字节数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字节数组,其中数组中的数据实际上是短期的数据。该字节以Little Endian下令:

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

,当在转换为短值的结果:

Which when converted to short values results in:

259,208,241,292

259, 208, 241, 292

有在Java中的简单方法的字节值转换为它们的对应的短的值?我可以写一个循环,只需要每一个高字节,由8位,其低字节接班和OR,但是,有一个性能命中。

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.

推荐答案

通过 java.nio.ByteBuffer中你可以指定你想要的字节顺序:<一href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#order%28java.nio.ByteOrder%29\">order().

With java.nio.ByteBuffer you may specify the endianness you want: order().

的ByteBuffer有方法提取数据字节,CHAR,<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#getShort%28%29\">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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆