Java中的LSB / MSB处理
如果必须处理以0x118之类的字节形式存储的值,如何拆分LSB和MSB?
我正在尝试以下方法…我认为这不是正确的方法:
value = 0x118;以字节为单位存储…
result[5] = (byte) value;  result[6] = (byte)(value << 8);  
...
正确的方法是什么?
回答:
这样做:
result[5] = (byte) (value & 0xFF);           // Least significant "byte"result[6] = (byte) ((value & 0xFF00) >> 8);  // Most significant "byte"
我通常使用位掩码-也许不需要它们。第一行选择低八位,第二行选择高八位,然后将这些位右移八位。这等于被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
概括起来,请进行以下计算:
 byte msb = result[6]; byte lsb = result[5];
 int result = (msb << 8) + lsb;    // Shift the MSB bits eight positions to the left.
以上是 Java中的LSB / MSB处理 的全部内容, 来源链接: utcz.com/qa/405211.html








