Ground Embedded KO Subscribe

Notes / Digital Logic

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.

GROUND EMBEDDED · NOTEDigital Logic 01Binary, hex and two's complementANDABY

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.

1010A01015= 0xA5decimal 165
The same value written three ways. One hex digit is four binary digits.

Two's complement

+50000 0101Invert1111 1010+ 1−51111 1011
Making a negative number. Invert every bit and add 1.

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
FREE PDFGet the 3 free ebooksIf you want to keep reading this topic as one book: BLDC motor control, serial communication and sensors at book length. PDFs are in Korean.Get them free →