Inside a QR Code
← → to move · type to change the code
Basics

How QR codes work

A QR code is a grid of black and white squares that stores text, survives scratches and stickers, and can be read at a slant from across a room.

This deck builds one from scratch, out of your message, using the same steps a real encoder follows. Then it breaks the code and watches it heal. Every picture is computed live; nothing is pre-drawn.

Error-correction level

This is a real, scannable code. Point a phone camera at it, then change the message and scan again.

Basics

Anatomy of a symbol

Each square is called a module. Some modules are fixed landmarks that every QR code has in the same place; the rest carry your data. Hover or tap a part to see what it does.

Sizes run from version 1 (21×21) to version 40 (177×177), adding 4 modules per side each step.

Data encoding

Text into bits

Before anything is drawn, your message becomes a stream of bits. It starts with a 4-bit mode indicator and a character count, then the data itself.

QR has several modes because packing matters. Digits are grouped in threes: 000–999 needs only 10 bits, because 210 = 1024. Uppercase letters, digits and nine symbols form a 45-character alphabet, so pairs fit in 11 bits (45² = 2025 ≤ 2048). Anything else is stored as UTF-8 bytes.

Go deeper: why these numbers?

Each mode is a small exercise in information theory. A decimal digit carries log₂10 ≈ 3.32 bits of information, so three digits need at least 9.97 bits; 10 bits wastes almost nothing. An alphanumeric pair carries log₂2025 ≈ 10.98 bits, so 11 bits is again nearly perfect.

numeric 3 digits → 10 bits (3.33 bits/char) alphanumeric 2 chars → 11 bits (5.5 bits/char) byte 1 byte → 8 bits (8 bits/char)

Real encoders can also switch modes partway through a message (for example a URL with a long number at the end) to save bits. That is a shortest-path problem, usually solved with dynamic programming.

Bit stream
The same message in each mode
Try:
Data encoding

Filling the box, one byte at a time

Each version and error-correction level has a fixed number of data codewords (bytes). The bit stream is finished off so it fills them exactly:

1. Up to four 0s as a terminator.
2. More 0s to reach a whole byte.
3. The pad bytes 11101100 (236) and 00010001 (17), alternating until the space is full.

The two pad bytes were chosen to look busy: their alternating bits avoid big blank areas that could confuse a scanner.

Capacity used
headeryour dataterminator + fillpad bytes
Bit stream
Data codewordsdecimal · binary
Data encoding

The zig-zag snake

The final codeword sequence (your data followed by the error-correction bytes we'll compute soon) is laid into the grid starting at the bottom-right corner.

Bits travel in columns two modules wide, snaking up, then down, then up again, and step around every landmark. Column 6 is skipped entirely because it holds the vertical timing pattern.

Hover a module to see which codeword and bit it holds. Each byte occupies a little 2×4 block, unless it has to bend around a corner.

speed

 

Error correction

What is error correction?

A QR code gets smudged, torn, printed badly, or partly covered by a logo. Some modules will be read wrong. Error correction adds carefully computed extra information so the reader can work out what the original was.

Try it: click bits in the received rows to flip them, as if the channel corrupted them. Then compare three ways of adding redundancy.

Repetition is simple but triples the size. Parity is cheap but can only say "something is wrong". Hamming(7,4) is cleverer. Its three check bits produce a syndrome that names the flipped position. That idea of computing exactly where the error is sits at the heart of QR's Reed–Solomon code.

Go deeper: errors, erasures, and the budget

Reed–Solomon works on whole bytes. A byte with 1 wrong bit or 8 wrong bits counts as one error, which makes it ideal for smudges and stains that wipe out clusters of modules.

With n − k check bytes, a decoder can fix e errors at unknown places and s erasures (bytes known to be bad) as long as:

2e + s ≤ n − k

Finding an error costs two check bytes: one to locate it and one to compute its value.

Message (click to change)
The math

A field of 256 numbers

Error correction needs real algebra on bytes: adding, multiplying, dividing, and solving equations. Ordinary arithmetic fails here. 200 + 100 doesn't fit in a byte, and dividing by 2 leaves fractions.

The fix is a finite field, called GF(2⁸) or GF(256). It has exactly 256 elements (every byte), and the arithmetic always stays inside:

Addition is XOR. No carries, and every number is its own negative, so subtracting is the same as adding.

Multiplication goes through powers of α = 2. Doubling repeatedly, and folding back with the polynomial 285 (0x11D) whenever the result spills past 8 bits, visits all 255 non-zero bytes before repeating. Every non-zero byte is some αⁱ, so multiplying becomes adding exponents.

Go deeper: why x⁸ + x⁴ + x³ + x² + 1?

Think of a byte as a polynomial with 0/1 coefficients: 0b10011 = x⁴ + x + 1. Field elements are these polynomials, taken modulo an irreducible degree-8 polynomial, much like clock arithmetic modulo a prime.

p(x) = x⁸ + x⁴ + x³ + x² + 1 → 1 0001 1101 = 0x11D = 285 α⁸ = α⁴ + α³ + α² + 1 (because p(α) = 0)

This p(x) is also primitive: α = x generates every non-zero element. That is what makes the log and antilog tables work. Every non-zero element has an inverse (a⁻¹ = α²⁵⁵⁻ˡᵒᵍ ᵃ), so division is always possible.

Powers of α: the cycle of 255

Byte calculator
The math

Reed–Solomon: division makes the check bytes

Treat your data codewords as the coefficients of a polynomial m(x). Multiply by xⁿ to make room for n check bytes, then divide by a fixed generator polynomial:

g(x) = (x − α⁰)(x − α¹)(x − α²) ··· (x − αⁿ⁻¹)

The remainder is the error-correction codewords. Data followed by remainder forms a polynomial that divides evenly by g(x), so it is zero at every α⁰ … αⁿ⁻¹. The decoder relies on exactly that property.

Each step: take the leading byte, multiply g(x) by it, XOR it away. Watch it run on your own codewords.

Go deeper: blocks and interleaving

Larger codes split the data into several blocks, each with its own check bytes. Then the bytes are interleaved: byte 1 of every block, then byte 2 of every block, and so on. A coffee stain that wipes out a run of neighbouring bytes is spread across many blocks, and each block only sees a few errors.

Robustness vs capacity at version
Long division in GF(256) · block 1

g(x) as exponents of α, highest power first:

Remainder = error-correction codewords
Error correction

Break it, watch it heal

Draw on the code, splash coffee on it, or stamp a logo in the middle. The reader runs live on every change. It reads the modules, removes the mask, splits the bytes back into blocks and runs a full Reed–Solomon decoder:

1. Syndromes. Evaluate the received polynomial at α⁰…αⁿ⁻¹. All zeros means no damage.
2. Berlekamp–Massey. Find the error-locator polynomial Λ(x), whose roots point at the bad bytes.
3. Chien search. Try every position to find those roots.
4. Forney. Compute how wrong each bad byte is, and XOR the fix in.

Push past the limit and decoding fails. Sometimes it is worse: the code lands on a different valid message.

Error-correction level
Damaged bytes per block (vs. what it can fix)
Decoder working, block 1
Finishing touches

Masking: making the pattern easy to read

Raw data can produce awkward patterns: big blank patches, long stripes, or shapes that look like a finder pattern. Any of these can mislead a scanner.

So the encoder XORs the data area with one of 8 fixed mask patterns, scores each result with four penalty rules, and keeps the lowest score. The reader undoes it with the same XOR, because (data ⊕ mask) ⊕ mask = data.

Go deeper: the four penalty rules

N1 runs of 5+ same-colour modules in a row or column: 3 points, +1 per extra module.
N2 every 2×2 block of one colour: 3 points.
N3 the pattern 1:1:3:1:1 next to 4 light modules, which looks like a finder: 40 points.
N4 dark-module share away from 50%: 10 points per 5%.

This is a brute-force optimization: try all 8 options and pick the best. It is cheap because the search space is tiny.

Penalty breakdown · mask
Finishing touches

Format info: a tiny code that protects the settings

Before reading anything else, the scanner needs two facts: the error-correction level (2 bits) and the mask (3 bits). Those 5 bits get their own error correction, a BCH(15,5) code. It is computed with polynomial division over plain bits, using the generator 10100110111.

The 10-bit remainder is appended, the result is XORed with 101010000010010 so it can never be all zeros, and the 15 bits are written twice around the finder patterns.

Go deeper: why it is so robust

There are only 32 valid format words, and any two differ in at least 7 of 15 bits. A reader compares what it sees with all 32 and picks the nearest. That fixes up to 3 wrong bits per copy, and there are two copies.

EC level
Mask
BCH division (bits)
15 format bits, bit 14 → bit 0 · hover one
Scanning

Finding the code at any angle

A camera frame is just pixels. The scanner first turns them into black and white (binarization), then scans across them looking for one signature: dark : light : dark : light : dark in the ratio 1 : 1 : 3 : 1 : 1.

That ratio is the trick. Any straight line through the centre of a finder pattern crosses its rings in the same proportions, whatever the angle, distance, or size. Ratios survive rotation and scaling, so the scanner never needs to know which way is up in advance.

Drag the yellow handles to move the scan line, rotate the code, then sweep to scan row by row as a real decoder does. Three clusters of hits mark three finders. The corner between the other two is top-left, and a cross product tells which of the others is top-right. Now the code's orientation is known.

Go deeper: global vs adaptive threshold

Turn on uneven lighting. With one global threshold, the shadowed white paper falls below 50% grey and turns black, and the finder ratios disappear. An adaptive threshold compares each pixel with the average of its neighbourhood (here a 25×25 window, using a summed-area table so each average costs four lookups).

Rotate
Runs along the scan line
Scanning

Undoing perspective

Photographed at a slant, the square grid becomes a skewed quadrilateral and the modules shrink with distance. The fix is projective geometry. A homography is a 3×3 matrix that maps any flat square onto any four-cornered view of it.

The scanner knows where four points should be: the centres of the three finders and the alignment pattern. It sees where they are. Four point pairs give eight equations, enough to solve for the eight unknowns of H. Then it samples the photo at the centre of every module.

Drag the four markers to tilt the paper. The right panel shows what the scanner reconstructs.

Go deeper: the equations
[x'] [h11 h12 h13] [u] [y'] ~ [h21 h22 h23] [v] x = x'/w, y = y'/w [w ] [h31 h32 1 ] [1] for each of 4 point pairs: h11·u + h12·v + h13 − h31·u·x − h32·v·x = x h21·u + h22·v + h23 − h31·u·y − h32·v·y = y

Solving the 8×8 linear system (Gaussian elimination) gives H. Larger versions have a whole lattice of alignment patterns, so a scanner can fit H locally and cope with paper that bends.

Camera view
Scanner's reconstruction
H (module space → camera pixels)
The big picture

Computer science and mathematics, end to end

A QR code is a small stack of ideas, each solving one problem. Click any stage to revisit it.

Encoding (printer side)
Decoding (camera side)
CSData compression

Bit packing

Three digits → 10 bits, two letters → 11 bits. Choosing the right mode is a variable-length encoding problem; mixing modes optimally is dynamic programming.

MathAbstract algebra

Finite fields

GF(2⁸): 256 bytes with XOR for addition and polynomial arithmetic mod x⁸+x⁴+x³+x²+1 for multiplication. Every non-zero byte has an inverse.

MathCoding theory

Reed–Solomon codes

Data as a polynomial; check bytes as a remainder. Errors show up as non-zero syndromes, Berlekamp–Massey finds the locator, Chien and Forney fix the values.

CSSystems

Interleaving

Spreading each block's bytes across the symbol turns one big burst of damage into a few small errors per block.

CSOptimization

Masking

Exhaustive search over 8 XOR patterns, scored by a hand-designed cost function, keeps the image scanner-friendly.

MathCyclic codes

BCH format info

5 bits become 15 bits with a minimum distance of 7. Nearest-codeword decoding fixes up to 3 bit errors per copy.

CSComputer vision

Detection

Adaptive thresholding with summed-area tables, then run-length matching of a ratio that does not change under rotation or scaling.

MathProjective geometry

Homography

Four point pairs, eight linear equations, one 3×3 matrix that undoes perspective so every module can be sampled at its centre.

The QR code was invented in 1994 by Masahiro Hara's team at Denso Wave to track car parts faster than barcodes allowed ("Quick Response"). It is standardised as ISO/IEC 18004. Reed–Solomon codes date from 1960 (Irving Reed and Gustave Solomon) and also protect CDs, DVDs, deep-space probes and RAID storage.