如果我必須處理以0x118字節存儲的值,那麼如何拆分LSB和MSB?Java中的LSB/MSB處理
我嘗試以下方法...我不認爲這是正確的方式:
value = 0x118;
字節存儲...
result[5] = (byte) value;
result[6] = (byte)(value << 8);
...
什麼是正確的方法是什麼?
如果我必須處理以0x118字節存儲的值,那麼如何拆分LSB和MSB?Java中的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 。
這是 「欺騙」 的背後:
(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.
是...它工作...如果你不介意..你能解釋我這個嗎? – 2011-03-02 12:04:39
嘿...一個問題...我總結了一下,看看我是否恢復了原始值System.out.println((result [5] + result [6])+「< --LSB + MSB \ n「);但我越來越25 < - LSB + MSB – 2011-03-02 12:08:48
我想我應該回來128 ... ...原始價值.... – 2011-03-02 12:10:07
在今天的Java版本,沒有必要手工操作。而且你不應該這麼做,因爲插入錯誤很容易。
只需使用:
short value = 0x118;
ByteBuffer.wrap(result).order(ByteOrder.LITTLE_ENDIAN).putShort(5, value);
這項任務。如您所願,類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);
或者更有效的方式來處理同一種價值觀的序列:
ByteBuffer.wrap(result).order(ByteOrder.LITTLE_ENDIAN)
.asShortBuffer().put(shortValue1).put(shortValue2).put(shortValue3);
當然,您還可以讀回數值:
System.out.printf("0x%x%n",
ByteBuffer.wrap(result).order(ByteOrder.LITTLE_ENDIAN).getShort(5));
對不起,如果這是一個愚蠢的問題,但'lsb'和'msb'是什麼? – DerMike 2011-03-02 11:58:43
LSB - 最低有效位*,最高有效位 - 最高有效位*(但Arun想要將一個短分爲*字節*) – 2011-03-02 12:00:14
這就是說,它意味着最低有效位和最高有效位 – 2011-03-02 12:00:29