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?
In today’s Java versions there is no need to do this by hand. And you shouldn’t do it as it’s easy to insert errors.
Simply use:
for this task. The class
ByteBuffer
provides methods for putting all primitive data types, in little endian or big endian byte order, as you wish. It also offers a way to put a heterogeneous sequence of values using an implied position:Or a more efficient way to handle a sequence of the same kind of values:
Of course, you can also read back the value:
This will do it:
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:
To sum it up, do the following calculation: