Number bases (binary & hex)
easy 14 minEvery number base works the same way: each digit is multiplied by the base raised to the power of its position.
Video lesson · Chapter 1 of 10
One byte, three readouts
Number bases (binary and hex)
1:27Reel
Read caption
Pip reads one rail of eight lanterns as binary, decimal and hexadecimal, then uses a bit mask to test one light. Each place doubles. Four bits make a hex digit.
How it works
Step through the idea, or press Play.
Position sets the value. A digit is worth digit times base to the power of its position, counting from 0 on the right
Understand it
Start here
What a number base is
A number base (or radix) is how many different digits a number system uses before it has to carry into the next place. Decimal has ten digits, 0 to 9, because humans count on ten fingers. Binary has two, 0 and 1. Hexadecimal has sixteen, 0 to 9 and then A to F. The value of a number never changes; only the way it is written does. Forty-two is 42 in decimal, 101010 in binary and 2A in hex.
Binary, base 2
Digits 0 and 1. Place values are powers of 2. The native language of hardware: every bit is a switch that is off or on.
Decimal, base 10
Digits 0 to 9. Place values are powers of 10. What people type and read, so all user-facing numbers are decimal.
Hexadecimal, base 16
Digits 0 to 9 and A to F. Place values are powers of 16. A compact way to write binary: one hex digit is four bits.
The one formula
Positional notation
All three systems are positional: a digit's position decides what it is worth. Number the positions from 0 on the right. A digit in position is worth , where is the base. Add those up and you have the value.
Value of a number in base b
Reading any number
| Base | Written | Expansion | Value |
|---|---|---|---|
| 10 | 42 | 40 + 2 = 42 | |
| 2 | 101010 | 32 + 8 + 2 = 42 | |
| 16 | 2A | 32 + 10 = 42 |
Base 10
Decimal, the base you already know
Decimal is the easiest place to see positional notation because you use it without thinking. The positions have names, ones, tens, hundreds, thousands, and each place is worth 10 times the place to its right.
Breaking down 1,234
Why decimal still matters in CS
Input and output
Every number a user types or reads is decimal, so programs convert at the edges.
The bridge
Converting between binary and hex by hand, or checking a result, usually goes through a decimal sum.
Floating point
0.1 has no exact binary form, so
0.1 + 0.2is0.30000000000000004. Decimal fractions and binary storage do not line up.
Base 2
Binary, the language of computers
At the hardware level a transistor is either off (0) or on (1). That is why every piece of data, text, images, video and code, is stored as binary. Each binary digit is a bit; the place values double as you move left: 1, 2, 4, 8, 16, 32, 64, 128.
Bit
One binary digit, 0 or 1.
Nibble
4 bits, values 0 to 15. Exactly one hex digit.
Byte
8 bits, values 0 to 255 (). Two hex digits, 00 to FF.
Word
32 or 64 bits depending on the CPU. A 32-bit unsigned int tops out at billion.
Powers of 2 to memorise
| Power | Value | Power | Value |
|---|---|---|---|
| 1 | 64 | ||
| 2 | 128 | ||
| 4 | 256 | ||
| 8 | 512 | ||
| 16 | 1,024 | ||
| 32 | 65,536 |
How many bits does n need?
(42).bit_length().Converting
Decimal to binary, two ways
Way 1: subtract the largest power that fits
Way 2: divide by 2 and keep the remainders
def by_place_values(n, width=8): bits = "" for p in range(width - 1, -1, -1): if 2 ** p <= n: bits += "1" n -= 2 ** p else: bits += "0" return bitsdef by_division(n): if n == 0: return "0" bits = "" while n > 0: bits = str(n % 2) + bits # prepend: first remainder is the lowest bit n //= 2 return bitsprint(by_place_values(42)) # 00101010print(by_division(42)) # 101010print(bin(42), f"{42:08b}") # 0b101010 00101010Back again
Binary to decimal
Going back is just the positional formula: add up the place values of the bits that are on. For 101010 that is . Code usually uses a neater form called Horner's method: scan left to right, and for each digit multiply the running total by the base and add the digit.
Horner's method
DIGITS = "0123456789ABCDEF"def from_base(s, base): total = 0 for ch in s.upper(): total = total * base + DIGITS.index(ch) return totalprint(from_base("101010", 2)) # 42print(from_base("2A", 16)) # 42print(int("101010", 2), int("2A", 16), int("0x2A", 0)) # 42 42 42Base 16
Hexadecimal, the programmer's shorthand
Binary is long: 255 is 11111111. Hex shortens it without losing the link to the bits. Hex needs sixteen digits, so after 9 it borrows letters: A = 10, B = 11, C = 12, D = 13, E = 14, F = 15. Place values are powers of 16: 1, 16, 256, 4096.
Why one hex digit is four bits
The sixteen nibbles
| Hex | Dec | Binary | Hex | Dec | Binary |
|---|---|---|---|---|---|
| 0 | 0 | 0000 | 8 | 8 | 1000 |
| 1 | 1 | 0001 | 9 | 9 | 1001 |
| 2 | 2 | 0010 | A | 10 | 1010 |
| 3 | 3 | 0011 | B | 11 | 1011 |
| 4 | 4 | 0100 | C | 12 | 1100 |
| 5 | 5 | 0101 | D | 13 | 1101 |
| 6 | 6 | 0110 | E | 14 | 1110 |
| 7 | 7 | 0111 | F | 15 | 1111 |
Hex and binary
Swap digits for nibbles
Converting between hex and binary
Two worked examples
HEX = "0123456789ABCDEF"def to_hex(n): if n == 0: return "0" out = "" while n > 0: out = HEX[n % 16] + out # 42 % 16 = 10 -> "A", then 2 -> "2" n //= 16 return outdef hex_to_bin(h): return " ".join(format(int(c, 16), "04b") for c in h)def bin_to_hex(b): b = b.zfill((len(b) + 3) // 4 * 4) # pad on the left to a multiple of 4 return "".join(HEX[int(b[i:i + 4], 2)] for i in range(0, len(b), 4))print(to_hex(42), to_hex(255)) # 2A FFprint(hex_to_bin("2A")) # 0010 1010print(bin_to_hex("11010110")) # D6print(f"{42:X} {42:#x} {255:02X}") # 2A 0x2a FFMust-know conversions
| Decimal | Binary | Hex | Why it matters |
|---|---|---|---|
| 0 | 0000 | 0 | Zero |
| 1 | 0001 | 1 | The lowest bit |
| 8 | 1000 | 8 | |
| 10 | 1010 | A | The first hex letter |
| 15 | 1111 | F | Largest single hex digit, a full nibble |
| 16 | 10000 | 10 | , the first two-digit hex number |
| 42 | 101010 | 2A | Our worked example |
| 127 | 01111111 | 7F | Largest signed 8-bit value |
| 128 | 10000000 | 80 | Only the top bit of a byte |
| 255 | 11111111 | FF | Largest byte value |
| 256 | 100000000 | 100 | , needs a ninth bit |
Any base
Converting between any two bases
Pick the route
chmod 755 is 111 101 101.The division method in general
Do
- Use
int(s, base)to parse andformat(n, "b"),"x"or"X"to print. - Pad with
format(n, "08b")when the width matters. - Go hex to binary digit by digit, four bits each.
- Special-case 0 in hand-written converters.
Avoid
- Forgetting that
bin()andhex()add0band0x. - Calling
int("2A")without a base: ValueError. - Reading division remainders top-down.
- Detouring through decimal to convert hex to binary.
Where you will see it
Bases in real systems
Memory addresses
Debuggers and stack traces print addresses in hex, such as
0x7FFF5FBFF8C0, because each digit maps to four address bits.Colours
#FF5733is three bytes: red FF = 255, green 57 = 87, blue 33 = 51.Unix permissions
chmod 755is octal: 7 = 111 (rwx) for the owner, 5 = 101 (r-x) for group and others.Networking
Each IPv4 octet, as in
192.168.1.1, is 8 bits (0 to 255). MAC addresses like00:1A:2B:3C:4D:5Eare six hex bytes.Bit flags
READ = 1, WRITE = 2, EXEC = 4 each own one bit, so READ | WRITE = 3 holds both.
Interview problems
Number of 1 bits, reverse bits, single number with XOR and power of two all start from reading a number as bits.
Binary patterns to recognise
| Pattern | Formula | Examples |
|---|---|---|
| All ones | 1111 = 15, 11111111 = 255 | |
| A single 1 then zeros | 1000 = 8, 10000000 = 128 | |
| Alternating 1 and 0 | repeat 10 | 1010 = 10, 101010 = 42, 10101010 = 170 |
| Power of two test | n & (n - 1) == 0 | 8 & 7 = 1000 & 0111 = 0 |
- 1You type 42decimal at the keyboard
- 2Stored as 00101010binary in memory
- 3Debugger shows 0x2Ahex for humans reading bits
One value, three views: people, hardware, and programmers in between.
Recap
Key takeaways
Key points
- Positional notation is universal: , with every digit smaller than the base.
- Binary is base 2 because hardware has two states. Place values are 1, 2, 4, 8 ... and needs bits.
- Decimal to any base: take
n % b, thenn //= b, and reverse the remainders. Any base to decimal: Horner,total = total * b + d. - Hex is compact binary: , so one hex digit is one nibble and two hex digits are one byte.
- Hex letters: A = 10 up to F = 15 (letter position plus 9). 0xFF = 255 is the largest byte.
- Memorise powers of 2 up to and the anchors 42 = 101010 = 0x2A.
- In Python:
int(s, base),bin,hex,format(n, "08b")andn.bit_length().