How to Convert Numbers Between Decimal, Binary, Hex, and Octal
Computers operate in binary, but humans prefer decimal. Developers use hexadecimal for color codes, memory addresses, and byte values. Understanding number bases and how to convert between them is a fundamental skill for anyone working close to the metal.
The Four Number Bases
| Base | Name | Digits | 255 in this base | Used for |
|---|---|---|---|---|
| Base 10 | Decimal | 0–9 | 255 | Everyday numbers |
| Base 2 | Binary | 0, 1 | 11111111 | CPU instructions, bitwise ops |
| Base 16 | Hexadecimal | 0–9, A–F | FF | Colors, memory addresses, hashes |
| Base 8 | Octal | 0–7 | 377 | Unix file permissions (chmod 755) |
Quick Reference Table (0–15)
| Dec | Bin | Hex | Oct | Dec | Bin | Hex | Oct |
|---|---|---|---|---|---|---|---|
| 0 | 0000 | 0 | 0 | 8 | 1000 | 8 | 10 |
| 1 | 0001 | 1 | 1 | 9 | 1001 | 9 | 11 |
| 2 | 0010 | 2 | 2 | 10 | 1010 | A | 12 |
| 3 | 0011 | 3 | 3 | 11 | 1011 | B | 13 |
| 4 | 0100 | 4 | 4 | 12 | 1100 | C | 14 |
| 5 | 0101 | 5 | 5 | 13 | 1101 | D | 15 |
| 6 | 0110 | 6 | 6 | 14 | 1110 | E | 16 |
| 7 | 0111 | 7 | 7 | 15 | 1111 | F | 17 |
Converting in Code
JavaScript
// Decimal → other bases
(255).toString(2); // "11111111" (binary)
(255).toString(16); // "ff" (hex)
(255).toString(8); // "377" (octal)
// Other bases → decimal
parseInt("11111111", 2); // 255
parseInt("ff", 16); // 255
parseInt("377", 8); // 255
// Hex literals in JS
const color = 0xFF5733; // decimal 16733987
const byte = 0b10110011; // binary literal = 179
const perm = 0o755; // octal literal = 493 Python
n = 255
bin(n) # '0b11111111'
hex(n) # '0xff'
oct(n) # '0o377'
# Literals
b = 0b11111111 # binary → 255
h = 0xFF # hex → 255
o = 0o377 # octal → 255
# String to int
int('ff', 16) # 255
int('11111111', 2) # 255 Practical Uses
CSS Colors (Hex)
#FF5733 = R:255, G:87, B:51. Each pair of hex digits represents one byte (0–255) of a color channel. #RGB shorthand: #F53 = #FF5533.
Unix Permissions (Octal)
chmod 755 = 111 101 101 in binary = rwx r-x r-x. Owner: 7=rwx, Group: 5=r-x, Other: 5=r-x.
Bitwise Operations
IP subnet masks, feature flags, and bitmasks are often expressed in binary or hex. 0xFF = 0b11111111 = all 8 bits set.
Memory Addresses
Debuggers and assembly use hex addresses: 0x7fff5fbff8a0. More compact than binary and easier to read than decimal for large numbers.
Convert between number bases instantly — free