开发者

LSB/MSB handling in Java

开发者 https://www.devze.com 2023-02-14 03:31 出处:网络
If I have to handle values to be stored in bytes like 0x118, how do I split the LSB and MSB? I was trying the following way... I d开发者_如何学Con\'t think that it\'s the right way:

If I have to handle values to be stored in bytes like 0x118, how do I split the LSB and MSB?

I was trying the following way... I d开发者_如何学Con't think that it's the right way:

value = 0x118;  

Storing in bytes...

result[5] = (byte) value;  
result[6] = (byte)(value << 8);  
...

What is the correct way?


This will do it:

result[5] = (byte) (value & 0xFF);           // Least significant "byte"
result[6] = (byte) ((value & 0xFF00) >> 8);  // Most significant "byte"

I usually use bit masks - maybe they're not needed. The first line selects the lower eight bits, the second line selects the upper eight bits and shifts the bits eight bit positions to the right. This is equal to a division by 28.


This is the "trick" behind:

  (I) LSB

  01010101 10101010        // Input
& 00000000 11111111        // First mask, 0x00FF
  -----------------
  00000000 10101010        // Result - now cast to byte

  (II) MSB

  01010101 10101010        // Input
& 11111111 00000000        // Second mask, 0xFF00
  -----------------
  01010101 00000000        // Result - 
  >>>>>>>>                 // "Shift" operation, eight positions to the right
  -----------------
  00000000 01010101        // Result - now cast to byte

To sum it up, do the following calculation:

 byte msb = result[6];
 byte lsb = result[5];
 int result = (msb << 8) + lsb;    // Shift the MSB bits eight positions to the left.


In today’s Java versions there is no need to do this by hand. And you shouldn’t do it as it’s easy to insert errors.

Simply use:

short value = 0x118;
ByteBuffer.wrap(result).order(ByteOrder.LITTLE_ENDIAN).putShort(5, value);

for this task. The class ByteBuffer provides methods for putting all primitive data types, in little endian or big endian byte order, as you wish. It also offers a way to put a heterogeneous sequence of values using an implied position:

ByteBuffer.wrap(result) // default big endian, start a offset 0
  .put(byteValue).putInt(123456).putShort(value)
  .order(ByteOrder.LITTLE_ENDIAN) // change for next values
  .putInt(400).putShort(value);

Or a more efficient way to handle a sequence of the same kind of values:

ByteBuffer.wrap(result).order(ByteOrder.LITTLE_ENDIAN)
  .asShortBuffer().put(shortValue1).put(shortValue2).put(shortValue3);

Of course, you can also read back the value:

System.out.printf("0x%x%n",
  ByteBuffer.wrap(result).order(ByteOrder.LITTLE_ENDIAN).getShort(5));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号