Why programmers use hex and binary
Computers store everything in binary, base 2, where each digit is a bit. Long binary numbers are hard to read, so programmers group them into fours. Each group of four bits is exactly one hexadecimal digit, 0 to 9 then A to F. That's why the byte 1010 0101 is written 0xA5, and why microcontroller registers and colour codes are given in hex.
| Decimal | Binary | Hex | Decimal | Binary | Hex |
|---|---|---|---|---|---|
| 0 | 0000 | 0 | 8 | 1000 | 8 |
| 1 | 0001 | 1 | 9 | 1001 | 9 |
| 2 | 0010 | 2 | 10 | 1010 | A |
| 3 | 0011 | 3 | 11 | 1011 | B |
| 4 | 0100 | 4 | 12 | 1100 | C |
| 5 | 0101 | 5 | 13 | 1101 | D |
| 6 | 0110 | 6 | 14 | 1110 | E |
| 7 | 0111 | 7 | 15 | 1111 | F |
Two's complement: how negative numbers are stored
Almost every processor stores signed integers in two's complement. In an 8-bit value, the top bit is worth −128 instead of +128, so the range is −128 to +127. To negate a number, flip every bit and add one: 5 is 0000 0101, so −5 is 1111 1011, which is 0xFB.
The same bits mean different things depending on the type. 0xC8 is 200 as an unsigned byte but −56 as a signed one. That's a classic bug when reading sensor registers: a temperature sensor that returns a signed 16-bit value has to be converted, or a reading of −1 shows up as 65,535. In Python:
raw = 0xFFF6 # 16-bit value read from a sensor
if raw & 0x8000: # top bit set, so it's negative
raw -= 0x10000
print(raw) # -10
Writing numbers in code
Python, C, C++, JavaScript and Arduino all accept 0x for hex and 0b for binary, for example 0xFF and 0b1010. Python uses 0o for octal, while C and Arduino treat any number starting with 0 as octal, so 010 is 8 there. Python converts with hex(), bin() and int("ff", 16).