Java中的LSB / MSB处理 [英] LSB/MSB handling in Java

查看:878
本文介绍了Java中的LSB / MSB处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;  

以字节存储...

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"

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

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.

这是背后的诡计 :

  (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.

这篇关于Java中的LSB / MSB处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆