Binary, hexadecimal and two's complement
Register values are read in hexadecimal, and negative numbers are stored in two's complement. The number sense needed to read datasheets and debugger screens.
Every value inside a computer is 0s and 1s. Writing 32 bits in binary is too long, so they are grouped four at a time into one hexadecimal digit.
| Binary | Hex | Decimal |
|---|---|---|
| 0000 | 0 | 0 |
| 1010 | A | 10 |
| 1111 | F | 15 |
When you meet an address such as 0x4002_0014 or a register value such as 0x3C, unfold it four bits at a time in your head. 0x3C is 0011 1100, so bits 2 to 5 are set.
Two's complement
A negative number is stored as "all bits inverted, plus 1". In 8 bits, −1 is 0xFF and −128 is 0x80. Done this way, a single adder circuit also handles subtraction.
The same 0xFF reads as 255 as a uint8_t and as −1 as an int8_t. This is why a 16-bit raw value from a sensor has to be received into a signed type.
int16_t accel = (int16_t)((buf[0] << 8) | buf[1]); // MPU6050 acceleration