Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

java - 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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...