Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting byte array values in little endian order to short values

Tags:

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.

like image 961
Johann Avatar asked Feb 12 '13 07:02

Johann


People also ask

What is little endian byte swap?

In little-endian style, the bytes are written from left to right in increasing significance. In big-endian style, the bytes are written from left to right in decreasing significance. The swapbytes function swaps the byte ordering in memory, converting little endian to big endian (and vice versa).

Does Endianness affect array order?

Endianness only affects the order of bytes (not bits) in a data word. Since a char is always one-byte in size, you don't have to do any adjustments to them.

How are arrays stored in memory Little endian?

In little-endian, the bytes are stored in the order least significant to most signficant. Big-endian is the opposite. For instance, short x=0x1234 would be stored as 0x34 , 0x12 in little-endian.

Does Endianness matter for a single byte?

Again, endian-ness does not matter if you have a single byte. If you have one byte, it's the only data you read so there's only one way to interpret it (again, because computers agree on what a byte is).


2 Answers

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... */ } 
like image 138
Aubin Avatar answered Sep 18 '22 15:09

Aubin


 /* 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;  } 
like image 43
Patrick Paulin Avatar answered Sep 18 '22 15:09

Patrick Paulin