LSB/MSB handling in Java

六月ゝ 毕业季﹏ 提交于 2019-12-30 01:12:21

问题


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 don'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?


回答1:


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.



回答2:


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));


来源:https://stackoverflow.com/questions/5167079/lsb-msb-handling-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!