🧮 Foundations — Before C
Hexadecimal & Octal: binary for humans
▶ Open the interactive lesson — free, no signupYou've already used hexadecimal without knowing it: every web color like #FF8800 is one, and so are the cryptic codes on a crashed blue screen. It's the shorthand that turns an unreadable wall of 0s and 1s into two characters per byte — and after this lesson you'll convert between the two in your head, no arithmetic required.
Binary is what machines speak, but for humans it's painfully verbose: a number like 0b11111111101010001001000000000000 is unreadable. Hexadecimal (base 16) fixes that: each hex digit packs exactly four bits, so any byte is just two characters.
Sixteen digits
Base 16 needs 16 symbols. We use 0–9, then borrow letters: A=10, B=11, C=12, D=13, E=14, F=15.
| binary | hex | dec | binary | hex | dec |
|---|---|---|---|---|---|
0000 | 0 | 0 | 1000 | 8 | 8 |
0001 | 1 | 1 | 1001 | 9 | 9 |
0010 | 2 | 2 | 1010 | A | 10 |
0011 | 3 | 3 | 1011 | B | 11 |
0100 | 4 | 4 | 1100 | C | 12 |
0101 | 5 | 5 | 1101 | D | 13 |
0110 | 6 | 6 | 1110 | E | 14 |
0111 | 7 | 7 | 1111 | F | 15 |
The trick: to convert binary ↔ hex you never do arithmetic — you just group bits in fours. 1011 0110 → B6. Done.
▶ This spot has an interactive baseconv widget — open the interactive lesson to play with it.
🧠 Checkpoint: What is hex 0x2F in decimal?
- 37
- 47
- 52
- 215
Show answer
47 — 0x2F = 2×16 + 15 = 47. The F is 15, and the 2 sits in the sixteens place.
Hex in C: the 0x prefix
#include <stdio.h>
int main(void) {
int color = 0xFF8800; /* an orange, as one int */
int red = (color >> 16) & 0xFF;
int green = (color >> 8) & 0xFF;
int blue = color & 0xFF;
printf("red=%d green=%d blue=%d\n", red, green, blue);
printf("42 is 0x%x in hex, %o in octal\n", 42, 42);
return 0;
}Notice %x in printf prints a value as hex, and %o prints octal (base 8, prefix 0 — a leading zero!).
Classic trap: in C, int x = 010; is octal — it means 8, not ten! A leading zero changes the base. Never zero-pad integer literals.
🧠 Checkpoint: In C, what is the value of int x = 011;?
- 11
- 9
- 3
- compile error
Show answer
9 — The leading zero makes it octal: 011 = 1×8 + 1 = 9. This surprising rule dates back to the 1970s — beware!
Where you'll meet hex daily
- Memory addresses:
0x7ffee4c01a2c— every pointer you'll ever print. - Colors:
#FF8800is just three bytes: red=0xFF, green=0x88, blue=0x00. - Bit masks:
value & 0x0Fkeeps the low nibble (4 bits — half a byte). - File formats: a PNG file always starts with bytes
89 50 4E 47.
🧠 Checkpoint: How many bits does one hex digit represent?
- 2
- 4
- 8
- 16
Show answer
4 — One hex digit covers exactly 16 values = 2⁴ = 4 bits (a "nibble"). That is why two hex digits describe a byte perfectly.