Java中的LSB/MSB处理

Aru*_*ham 15 java byte bytearray

如果我必须处理以0x118为单位存储的值,我该如何拆分LSB和MSB?

我正在尝试以下方式...我不认为这是正确的方式:

value = 0x118;  
Run Code Online (Sandbox Code Playgroud)

以字节存储...

result[5] = (byte) value;  
result[6] = (byte)(value << 8);  
...
Run Code Online (Sandbox Code Playgroud)

什么是正确的方法?

And*_*s_D 29

这样做:

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

我通常使用位掩码 - 也许他们不需要.第一行选择低8位,第二行选择高8位,并将位8位位置向右移位.这相当于除以2 8.


这是背后的"伎俩":

  (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
Run Code Online (Sandbox Code Playgroud)

总结一下,做以下计算:

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


Hol*_*ger 10

在今天的Java版本中,没有必要手动执行此操作.你不应该这样做,因为插入错误很容易.

只需使用:

short value = 0x118;
ByteBuffer.wrap(result).order(ByteOrder.LITTLE_ENDIAN).putShort(5, value);
Run Code Online (Sandbox Code Playgroud)

为了这个任务.该类ByteBuffer 提供了根据需要以小端或大端字节顺序放置所有原始数据类型的方法.它还提供了一种使用隐含位置来放置异构值序列的方法:

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);
Run Code Online (Sandbox Code Playgroud)

或者是处理相同类型值序列的更有效方法:

ByteBuffer.wrap(result).order(ByteOrder.LITTLE_ENDIAN)
  .asShortBuffer().put(shortValue1).put(shortValue2).put(shortValue3);
Run Code Online (Sandbox Code Playgroud)

当然,您也可以回读这个值:

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