Why do you need to multiply by 256 and add some bits when reading analog?

See this: https://github.com/DexterInd/GrovePi/blob/master/Software/Python/grovepi.py#L223
The raw bytes need to be multiplied by 256 (or left shifted by 8) and then added (or OR’ed) to another group of bytes. Why is that so?

Hi @LuCavallin,

Because that’s how casting 8-bit numbers to 16-bit numbers works - and for every any kind of combination. What you would want to do is search for Bitwise Operations or for Bit Shifting on Google - that should give you an insight into how concatenating 8-bit numbers into a multiplier of them works.

Basically, in a 16-bit configuration, we can fit 2 bytes. In order to do so, we need to make sure they don’t overlap once we add them. If for instance we add 2 bytes, one to each other, the end result won’t be a 16-bit number, but it will still be an 8-bit number (probably overflowed).
So in order to fix this, we need the first byte to be put in the left side of that 16-bit number and the 2nd one in the right side. To do so, we can shift the first 8-bit number by exactly 8 positions to the left. The mathematical equivalency is 2^8 = 256, which means bit-shifting it 8 positions is the same as multiplying the number by 256. Adding the 2nd byte to the already multiplied number makes the 2nd byte “fit” in the right side of the 16-bit number.

Hope all this makes sense for you. Here’s also a post on that deals with calculating a 32-bit number out of 4 8-bit numbers:

Thank you!