Basic

Hexadecimal

Hex is a sixteen-digit shorthand for bits. Each hex digit is exactly four bits, so a byte is two digits, and reading hex is far easier than reading a long row of ones.

What you will see

b'owl'

About 2 min of reading

Try It

Read and write hex.

1

Print what ff means.

print(0xff)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
255
2

Show the bits of one hex digit.

print(bin(0xf))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
0b1111
3

Print bytes as hex pairs.

print(b"\x00\x01\xff".hex())

Before you run it, say out loud what it will print. Then open the answer.

What it prints
0001ff
4

Turn hex back into bytes.

print(bytes.fromhex("6f776c"))

Before you run it, say out loud what it will print. Then open the answer.

What it prints
b'owl'

Data Flow

Hex is a sixteen-digit shorthand where each digit is four bits, so a byte is always two hex digits.
1 one hex digit is four bits
↓
2 a byte is two digits
↓
3 ff is 255
↓
4 hex is a display choice
Line by line

Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.

print(0xff) 255
Why this works
Hex is a display choice

The bits in memory do not change when you write them as hex. Hex is for humans, and it groups bits where bytes begin.

Where hex shows up

Colors, file signatures, hashes, and byte dumps are all hex. Learning to read pairs of digits covers all of them.

Examples

Hex digits

print(0xff)

The digit f is fifteen, so ff is 255. Hex is a shorter way to write the same bits, not a different value.

Four bits per digit

print(bin(0xf))
print(bin(0x1))

One hex digit is four bits. That is why a byte is always two hex digits, side by side.

Bytes as hex

print(b"\x00\x01\xff".hex())

A row of bytes prints as pairs of hex digits. That is what a hex editor shows you.

Hex back to bytes

print(bytes.fromhex("6f776c"))

Hex text turns back into bytes. The pairs are read two at a time, left to right.

Colors are hex

print(int("ff", 16))

A color is three bytes written as six hex digits. The same rule reads a color and reads a file.

Base sixteen

print(int("ff", 16))
print(int("10", 16))

Reading text as base sixteen gives 255 and 16. The base says how much each position is worth.

Why hex and not octal

print(0b1111 == 0xf)

Hex groups bits by four, which lines up with bytes. Octal groups by three and does not, so hex won.

Reading a dump

print("48656c6c6f".hex())

Hex pairs are bytes. Two hex digits per byte is the rhythm that makes a dump readable.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Bytes and the sizes they measure
Previous Lesson
Bytes and the sizes they measure
Next Lesson
Text stored as numbers
Text stored as numbers →