Binary and hexadecimal conversion explained
6 min readUpdated
Number conversion is in almost every computer science exam. Computers store everything in binary, and hexadecimal is a short way for humans to write binary. With place values you can convert any way in a minute.
Place value is the key idea
In denary (base 10) each column is worth 10 times the one to its right. In binary (base 2) each column is worth 2 times, and in hexadecimal (base 16) each column is worth 16 times.
| 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
|---|---|---|---|---|---|---|---|
| 1 | 0 | 1 | 1 | 0 | 1 | 0 | 0 |
Denary to binary
- Write the column values 128, 64, 32, 16, 8, 4, 2, 1.
- Start at the left: if the column fits into what is left, write 1 and subtract it; otherwise write 0.
- Carry on until you reach the 1 column.
Example: 77. 64 fits (13 left), 32 no, 16 no, 8 fits (5 left), 4 fits (1 left), 2 no, 1 fits. Answer: 01001101.
Hexadecimal digits
| Denary | Binary | Hex |
|---|---|---|
| 9 | 1001 | 9 |
| 10 | 1010 | A |
| 11 | 1011 | B |
| 12 | 1100 | C |
| 13 | 1101 | D |
| 14 | 1110 | E |
| 15 | 1111 | F |
Binary to hex and back
One hex digit is exactly four bits (a nibble). Split the binary into groups of four from the right, then convert each group.
1011 0100
B 4 -> B4
3F -> 0011 1111Hex to denary
Multiply the left digit by 16 and add the right digit. B4 = 11 × 16 + 4 = 180, the same as the binary example above.
Check your answers with Python
print(bin(77)) # 0b1001101
print(hex(180)) # 0xb4
print(int("10110100", 2)) # 180
print(int("B4", 16)) # 180Common mistakes
- Grouping bits from the left instead of the right.
- Forgetting that A to F stand for 10 to 15.
- Dropping leading zeros when the question asks for 8 bits.
- Mixing up which column is 1 (it is always the rightmost).
Frequently asked questions
Why do programmers use hexadecimal?
It is much shorter than binary and converts to it easily, so it is used for colour codes, memory addresses and error codes.
What is the largest number in 8 bits?
11111111, which is 255 in denary and FF in hex.
Do I need to learn the hex table by heart?
Learning 10 to 15 as A to F is enough; everything else comes from place value.
Learn it step by step
Practise this, step by step
Short lessons with quizzes, practice and interview questions, from your first program to job-ready.