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?
解决方案
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.