9. QR Codes: How They Work and How They're Generated
From HELLO WORLD to a scannable symbol by hand: encoding modes, Reed-Solomon over GF(256), the zigzag, the eight masks and the format bits
Picture a car-parts factory in early-1990s Japan. Every crate of components carries a kanban card, and every card has to be scanned, again and again, as the parts move down the line. The barcodes of the day hold only about twenty characters, nowhere near enough for everything the factory would like each label to say. The cards get greasy and torn, get held at odd angles, and get scanned by people in a hurry. What the factory wants is a label that holds a lot more, can be read from any direction in a fraction of a second, and still works when a corner is covered in oil.
That was the brief Masahiro Hara's small team at Denso Wave (then a division of the Toyota-group supplier Denso) worked to. In 1994 they released the answer: the QR Code, short for Quick Response. Three decades later it's on restaurant tables, boarding passes, parcels and payment terminals. Denso Wave kept the patent but announced it would not enforce it, which is a large part of why it spread everywhere.
A QR code is a great final stop for this series because it's a small, complete, real-world
error-correction system you can build by hand. It uses the
Reed-Solomon codes from earlier, it interleaves them
across blocks, and it protects its own header with a BCH code, a close cousin of the
Hamming codes. In this article we'll take the eleven characters HELLO WORLD
and turn them, bit by bit, into the symbol below. Every number on the way is real: you can check
each step, and your phone can scan the result.
The Big Picture
Making a QR code is a pipeline. Each stage hands a sequence of bits or bytes to the next, and only the last few stages care about the 2D grid at all.
- Analyse the text. Pick the most compact encoding mode (numeric, alphanumeric, byte or kanji) and the smallest version (size) that fits at the chosen error-correction level.
- Build the data bit stream. Mode indicator, character count, the encoded characters, a terminator, then padding up to the exact capacity.
- Add error correction. Split the data bytes into blocks and compute Reed-Solomon check bytes for each block.
- Interleave. Weave the blocks together so that one damaged patch of the symbol hurts every block a little, rather than one block a lot.
- Draw the fixed patterns. Finder, separator, timing and alignment patterns, and the dark module.
- Place the bits. Snake the final bit sequence through the remaining modules in a two-column zigzag.
- Mask. Try all eight mask patterns, score each with four penalty rules, keep the best.
- Write the format (and version) information so a scanner knows the error-correction level, the mask and the size.
Before we start pushing bits, let's learn our way around the symbol.
Anatomy of a QR Code
A QR code is a square grid of modules, the little black or white squares. Most modules carry data, but a good fraction are function patterns: fixed shapes that exist purely to help a camera find the symbol, work out its orientation and size, and measure the grid. Here is a version 7 symbol (45 × 45 modules) with every kind of module coloured in:
Finder patterns. The three big squares in the corners. Each is a 7 × 7 dark ring, a light ring, and a 3 × 3 dark core. Draw a line through the centre in any direction, horizontally, vertically or diagonally, and you cross dark, light, dark-dark-dark, light, dark in the ratio 1 : 1 : 3 : 1 : 1. A scanner just looks for that ratio in its scan lines. Denso Wave picked it after surveying printed material (flyers, magazines, cardboard boxes) for the black-and-white width ratio that turned up least often, so ordinary print rarely fools the detector. Three corners rather than four tells the scanner which way up the symbol is: the empty corner is bottom-right.
Separators. A one-module light border around each finder pattern, so the 1 : 1 : 3 : 1 : 1 ratio isn't spoiled by data modules that happen to be dark next to it.
Timing patterns. Row 6 and column 6 alternate dark-light-dark between the finders. They let the scanner count modules and measure the grid pitch, even if the print is slightly stretched.
Alignment patterns. Smaller 5 × 5 targets (dark ring, light ring, dark centre) that appear from version 2 upward. Big symbols get photographed with perspective and curvature, and alignment patterns give the scanner extra reference points in the interior to correct for that. Their centres sit on a version-dependent list of coordinates, used for both rows and columns, with the three combinations that would collide with the finders left out:
| Version | Centre coordinates | Patterns |
|---|---|---|
| 1 | none | 0 |
| 2 | 6, 18 | 1 |
| 7 | 6, 22, 38 | 6 |
| 14 | 6, 26, 46, 66 | 13 |
| 40 | 6, 30, 58, 86, 114, 142, 170 | 46 |
For version 2 and up, each axis has ⌊v/7⌋ + 2 coordinates, so version 40 has 7 × 7 − 3 = 46 alignment patterns.
The dark module. One module next to the bottom-left finder, at row 4v + 9, column 8, is always dark. It carries no information. (Row 13 in version 1.)
Format information. Fifteen bits, written twice: once wrapped around the top-left finder, once split between the other two. They tell the scanner the error-correction level and which mask was used, and they're protected by their own BCH code. We'll compute them near the end.
Version information. For version 7 and up, eighteen bits stating the version, written twice in 6 × 3 blocks beside the top-right and bottom-left finders. Smaller symbols don't need it: a scanner can work out versions 1 to 6 from the module count reliably.
Quiet zone. A blank margin, four modules wide on every side. It isn't part of the grid, but without it the finder ratio blurs into whatever is printed nearby. Codes printed edge-to-edge on a busy background are a common reason a QR code "doesn't scan".
Everything else, the pale grey area above, is the encoding region: data codewords, error correction codewords and, sometimes, a few leftover remainder bits.
Versions and Sizes
QR codes come in forty sizes called versions. Version 1 is 21 × 21 modules, and every version adds four modules to each side:
So version 2 is 25 × 25, version 10 is 57 × 57 and version 40 is 177 × 177. Once you subtract the function patterns, what's left is divided into 8-bit codewords (bytes). A few modules can be left over that don't make a whole codeword; those are the remainder bits (0, 3, 4 or 7 of them depending on the version), and they're simply filled with zeros.
| Version | Size | Total codewords | Remainder bits | Max chars at L (numeric / alphanumeric / byte) |
|---|---|---|---|---|
| 1 | 21 × 21 | 26 | 0 | 41 / 25 / 17 |
| 2 | 25 × 25 | 44 | 7 | 77 / 47 / 32 |
| 5 | 37 × 37 | 134 | 7 | 255 / 154 / 106 |
| 10 | 57 × 57 | 346 | 0 | 652 / 395 / 271 |
| 40 | 177 × 177 | 3,706 | 0 | 7,089 / 4,296 / 2,953 |
How many of those codewords hold your data depends on the error-correction level, which we'll get to shortly. Encoders normally pick the smallest version that fits, since smaller symbols have bigger modules at a given print size and scan more easily.
Text to encode
Stage
Data bit stream
Codewords
Mask penalties
Click a row to force that mask. Any mask gives a valid, scannable symbol; the scores only pick which one.
Format and version information
Encoding Modes: Choosing the Alphabet
Text gets turned into bits in one of several modes, each tuned to a different alphabet. The smaller the alphabet, the fewer bits per character:
| Mode | Characters | Packing | Bits per char |
|---|---|---|---|
| Numeric | 0–9 |
3 digits → 10 bits (2 → 7, 1 → 4) | ≈ 3.33 |
| Alphanumeric | 0–9, A–Z, space, $ % * + - . / : (45 total) |
2 chars → 11 bits (1 → 6) | 5.5 |
| Byte | any 8-bit value | 1 byte → 8 bits | 8 |
| Kanji | Shift JIS double-byte characters | 1 char → 13 bits | 13 per 2-byte char |
Every chunk of data starts with a 4-bit mode indicator, followed by a character count indicator whose width depends on both the mode and the version. Bigger symbols can hold longer strings, so they need wider counters:
| Mode | Indicator | Count bits, v1–9 | v10–26 | v27–40 |
|---|---|---|---|---|
| Numeric | 0001 |
10 | 12 | 14 |
| Alphanumeric | 0010 |
9 | 11 | 13 |
| Byte | 0100 |
8 | 16 | 16 |
| Kanji | 1000 |
8 | 10 | 12 |
| ECI | 0111 |
(no count; 8, 16 or 24-bit designator follows) |
There are also indicators for structured append (0011, splitting one message over up to 16
symbols) and FNC1 (0101, 1001, used by GS1 barcode standards). The terminator 0000 marks
the end of the data.
Numeric mode
Split the digits into groups of three and write each group as a 10-bit number. A final group of
two digits takes 7 bits, a lone digit takes 4. Here is 01234567 (8 digits) in a version 1 symbol:
Mode 0001 Count (8) 0000001000 (10 bits in versions 1–9) "012" = 12 0000001100 "345" = 345 0101011001 "67" = 67 1000011 (2 leftover digits → 7 bits)
Ten bits can hold 0–1023, which comfortably covers 000–999, so numeric mode wastes almost nothing.
Alphanumeric mode
Each character maps to a value 0–44: digits are 0–9, A–Z are 10–35, and then
space = 36, $ = 37, % = 38, * = 39, + = 40, - = 41, . = 42, / = 43, : = 44.
Take characters in pairs and encode 45 × first + second in 11 bits (the largest possible value,
44 × 45 + 44 = 2024, fits under 2048). An odd last character gets 6 bits.
"AC-42" Mode 0010 Count (5) 000000101 "AC" = 10×45+12 = 462 00111001110 "-4" = 41×45+4 = 1849 11100111001 "2" = 2 000010
Notice there are no lowercase letters. That's a surprisingly useful fact for URLs: scheme and
host names are case-insensitive, so HTTPS://EXAMPLE.COM/ encodes in alphanumeric mode at 5.5
bits per character instead of 8.
Byte mode
Raw bytes, 8 bits each. The count is the number of bytes, not characters. The standard says that
without further instructions, the bytes are ISO 8859-1 (Latin-1). In practice almost every
generator writes UTF-8 and almost every phone guesses UTF-8, so héllo becomes six bytes,
68 C3 A9 6C 6C 6F, with a count of 6.
Kanji mode
Designed for Japanese text in Shift JIS. Every double-byte character in the ranges 8140–9FFC
and E040–EBBF (hex) is squeezed into 13 bits: subtract 8140 (or C140 for the second range),
then compute high byte × C0 + low byte. For example 点 is Shift JIS 935F:
935F − 8140 = 121F, then 12 × C0 + 1F = D9F, written as 0110110011111. That's 13 bits for a
character that would cost 16 in byte mode.
ECI: saying which character set you mean
The Extended Channel Interpretation mode lets you announce the character set explicitly. It's
the mode indicator 0111 followed by an ECI designator: 8 bits for values 0–127 (0xxxxxxx),
16 bits up to 16383 (10xxxxxx …), 24 bits up to 999999 (110xxxxx …). ECI 26 means UTF-8, so a
strictly correct UTF-8 code starts with 0111 00011010 and then a normal byte-mode segment. Many
generators skip it, and many readers ignore it.
Mixing modes
A symbol can contain several segments, each with its own mode indicator and count. A product
code like ABC-1234567890 is cheaper as an alphanumeric segment followed by a numeric segment than
as one long alphanumeric run, because switching costs a 4-bit indicator plus a count but saves
about 2 bits per digit. Finding the optimal split is a small dynamic-programming problem; the
generator above keeps things simple and uses a single mode.
Building the Data Bit Stream
Now the worked example. We'll encode HELLO WORLD at version 1, level M. Every character is in
the alphanumeric set, so that's our mode. Version 1-M has room for exactly 16 data codewords,
128 bits, which is the length the bit stream has to end up at.
Step 1: Mode indicator and count
Mode (alphanumeric) 0010 Count (11 chars, 9 bits) 000001011
Step 2: Characters in pairs
"HE" 17×45 + 14 = 779 01100001011 "LL" 21×45 + 21 = 966 01111000110 "O " 24×45 + 36 = 1116 10001011100 "WO" 32×45 + 24 = 1464 10110111000 "RL" 27×45 + 21 = 1236 10011010100 "D" 13 001101 (odd one out: 6 bits)
So far: 4 + 9 + 5 × 11 + 6 = 74 bits.
Step 3: Terminator
Append up to four 0 bits (fewer if the capacity is nearly full). 74 + 4 = 78 bits.
Step 4: Pad to a byte boundary
78 is not a multiple of 8, so add two more 0s. 80 bits = 10 bytes.
Step 5: Pad bytes
Fill the remaining 6 bytes by alternating 11101100 (0xEC, 236) and 00010001 (0x11, 17).
The 128-bit data stream, cut into codewords
00100000 01011011 00001011 01111000 11010001 01110010 11011100 01001101 01000011 01000000 11101100 00010001 11101100 00010001 11101100 00010001 Decimal: 32 91 11 120 209 114 220 77 67 64 236 17 236 17 236 17 Hex: 20 5B 0B 78 D1 72 DC 4D 43 40 EC 11 EC 11 EC 11
Why 0xEC and 0x11 rather than zeros? Long runs of zero bytes would produce big uniform areas in
the symbol, which the masking step would then have to fight. The alternating 11101100 00010001
pattern is busy enough to keep the texture lively. Decoders just stop reading at the terminator
(or when the data runs out), so pad bytes are never mistaken for data.
Error Correction: Reed-Solomon, QR Style
Now we protect those 16 bytes. QR offers four error-correction levels. Each version and level has a fixed number of EC codewords, chosen so that roughly the stated fraction of codewords can be restored:
| Level | Format bits | Restores about | Version 1: data + EC codewords |
|---|---|---|---|
| L (Low) | 01 |
7% | 19 + 7 |
| M (Medium) | 00 |
15% | 16 + 10 |
| Q (Quartile) | 11 |
25% | 13 + 13 |
| H (High) | 10 |
30% | 9 + 17 |
(Yes, the two-bit codes really are in that odd order: L is 01 and M is 00. Don't try to sort
by them.)
The check bytes are a Reed-Solomon code over GF(256), exactly as described in the
Reed-Solomon article: bytes are field elements, addition is XOR, and
multiplication is done modulo the
irreducible polynomial
x⁸ + x⁴ + x³ + x² + 1, which is 0x11D, or 285. The primitive element α is 2, so the powers of α
run 1, 2, 4, 8, 16, 32, 64, 128, and then α⁸ = 256 XOR 285 = 29, and so on through all 255 non-zero
bytes.
The generator polynomial
For n EC codewords, the generator polynomial has the roots α⁰, α¹, …, αⁿ⁻¹:
One detail differs from the toy example in the Reed-Solomon article: QR's roots start at α⁰ = 1, not α¹. Since subtraction is XOR in GF(256), x − αⁱ is the same as x + αⁱ. For 1-M we need n = 10, which gives:
Generator polynomial for 10 EC codewords
As integers: g(x) = x¹⁰ + 216x⁹ + 194x⁸ + 159x⁷ + 111x⁶ + 199x⁵
+ 94x⁴ + 95x³ + 113x² + 157x + 193
Coefficients: 1 216 194 159 111 199 94 95 113 157 193
As α-powers: 0 251 67 46 61 118 70 64 94 32 45
(bottom row = the exponent k in αᵏ)
Writing the coefficients as powers of α is handy, because multiplying two field elements then just means adding exponents mod 255.
Dividing to get the check bytes
Treat the 16 data bytes as the coefficients of a message polynomial, highest power first, multiply it by x¹⁰ to make room, and divide by g(x). The 10 coefficients of the remainder are the EC codewords. Each step of the long division cancels the leading term:
Step 1: lead term 32 = α⁵
Multiply g by α⁵ (add 5 to every exponent, mod 255): exponents 5 1 72 51 66 123 75 69 99 37 50 values 32 2 101 10 97 197 15 47 134 74 5 XOR with the first 11 message terms: message 32 91 11 120 209 114 220 77 67 64 236 result 0 89 110 114 176 183 211 98 197 10 233
Step 2: drop the 0, bring down the next byte (17); lead term 89 = α²¹⁰
α²¹⁰·g 89 83 234 2 76 202 3 90 140 176 1 message 89 110 114 176 183 211 98 197 10 233 17 result 0 61 152 178 251 25 97 159 134 89 16
Steps 3–16: repeat
Fourteen more rounds of the same thing, one per remaining data byte. What's left at the end is the remainder.
The finished 1-M codeword sequence
Data (16): 32 91 11 120 209 114 220 77 67 64 236 17 236 17 236 17 EC (10): 196 35 39 119 235 215 231 226 93 23
Ten EC codewords would correct five errors in a textbook RS code. The QR standard is a little more cautious for its smallest symbols: it holds back a few codewords as misdecode protection, so a random smudge can't be "corrected" into a different but valid message. For 1-M it reserves two, so this symbol corrects up to 4 wrong codewords. (A decoder that knows which codewords are unreadable, so-called erasures, can recover a few more, since locating an error is half the work.)
Blocks and interleaving
A Reed-Solomon codeword over GF(256) can be at most 255 bytes long, and a version 40 symbol holds 3,706. So larger symbols split their data into several blocks, each with its own RS code. When the data doesn't divide evenly, the blocks come in two groups, and the second group's blocks carry one extra data byte. Version 5-Q is a nice small example:
Version 5-Q: 134 codewords = 62 data + 72 EC, in 4 blocks
Group 1: Block 1 15 data + 18 EC
Block 2 15 data + 18 EC
Group 2: Block 3 16 data + 18 EC
Block 4 16 data + 18 EC
Every block gets the same number of EC codewords (18).
The blocks aren't written one after another. As in the interleaving article, they're woven together column by column: first byte of every block, second byte of every block, and so on. Blocks that run out early are skipped. Then the EC bytes are interleaved the same way:
B1d1 B2d1 B3d1 B4d1 B1d2 B2d2 B3d2 B4d2 … B1d15 B2d15 B3d15 B4d15 B3d16 B4d16 B1e1 B2e1 B3e1 B4e1 … B1e18 B2e18 B3e18 B4e18 then 7 remainder bits (0000000) for version 5
Our HELLO WORLD symbol is version 1, which has a single block, so the final sequence is just the
16 data codewords followed by the 10 EC codewords: 26 bytes, 208 bits. Version 1 has exactly 208
data modules and no remainder bits.
Placing the Bits: The Zigzag
With the function patterns drawn, the 208 bits go into the free modules in a fixed order. Start at the bottom-right corner and work in two-module-wide columns:
- Within a column pair, take the right module, then the left, then move one row.
- Go up the first pair, then down the next, alternating, from right to left across the symbol.
- Skip any module that belongs to a function pattern or the format area.
- Column 6 is the vertical timing pattern, so when the pairs reach it, shift over by one and carry on with columns 5 and 4.
Each codeword's eight bits are placed most significant bit first. In a straight stretch, a codeword fills a 2 × 4 block:
Near the top and bottom edges and around function patterns, codewords bend into irregular shapes, but the rule never changes: next free module in the snake gets the next bit. Here are all 26 codewords of a version 1 symbol, with data in teal and EC in blue:
The first codeword, D1 = 32 = 00100000, lands in the bottom-right 2 × 4 block: bit by bit,
(row 20, col 20) = 0, (20, 19) = 0, (19, 20) = 1, (19, 19) = 0, and the remaining four are 0.
Masking: Making the Pattern Easy to Read
The symbol could stop here, but the data might accidentally contain trouble: a big solid block, long stripes, or a shape that looks like a finder pattern in the middle of the code. Any of those can confuse a scanner. The fix is to XOR the encoding region with a fixed pattern, called a mask, which scrambles any structure in the data. The scanner learns which mask was used from the format information and XORs it off again.
There are eight masks. With i as the row and j as the column, both counted from 0 at the top left, a module is flipped wherever the mask's condition is true:
Masks apply only to the data and EC modules. Function patterns, format information and version information are never masked.
Scoring a mask: the four penalty rules
The encoder applies each of the eight masks in turn, writes the matching format information, and adds up penalty points for features that are hard to scan. The mask with the lowest total wins.
| Rule | What it penalises | Points |
|---|---|---|
| N1 | A run of 5 or more same-coloured modules in a row or column | 3 for a run of 5, +1 per extra module |
| N2 | Each 2 × 2 block of one colour (overlapping blocks all count) | 3 each |
| N3 | The finder-like sequence dark-light-dark-dark-dark-light-dark (1011101) with 4 light modules on one side, i.e. 10111010000 or 00001011101, in any row or column |
40 each |
| N4 | Dark modules far from 50% of the symbol | 10 for every full 5% away from 50% |
N1 and N2 discourage big blobs and long stripes that make module counting hard. N3 is the heavyweight: a false finder pattern inside the code can genuinely mislead a detector. N4 keeps the overall balance close to half dark, which helps a camera set its black/white threshold.
For HELLO WORLD at 1-M, the eight candidates score like this (row and column runs, and
10111010000 / 00001011101 matches within the 21 × 21 grid):
| Mask | N1 | N2 | N3 | N4 | Total |
|---|---|---|---|---|---|
| 0 | 172 | 99 | 40 | 0 | 311 |
| 1 | 182 | 144 | 80 | 0 | 406 |
| 2 | 205 | 117 | 120 | 0 | 442 |
| 3 | 196 | 147 | 120 | 0 | 463 |
| 4 | 183 | 144 | 40 | 0 | 367 |
| 5 | 194 | 174 | 160 | 0 | 528 |
| 6 | 186 | 129 | 80 | 0 | 395 |
| 7 | 165 | 120 | 160 | 0 | 445 |
Mask 0 wins, the plain checkerboard. Every candidate is within 45–55% dark (mask 0 has 222 dark
modules out of 441, 50.3%), so N4 contributes nothing here. Mask 0 flips every module where
i + j is even, so the bottom-right block that held 0, 0, 1, 0, … before masking ends up
reading 1, 0, 1, 1, 1, 0, 0, 1.
Before masking
Data and EC bits as placed, format area still blank.
After mask 0 + format info
The finished symbol, ready to print.
Mask
Penalty rules to highlight
Format Information: The Symbol's Header
A scanner can't unmask or error-correct anything until it knows the error-correction level and the mask. Those five bits (2 for the level, 3 for the mask) are the format information, and if they're wrong, nothing else matters. So they get their own, much stronger, error correction: a BCH(15, 5) code that adds 10 check bits.
The check bits are the remainder of dividing the 5 data bits, shifted left by 10, by the generator
(10100110111 in binary), using XOR in place of subtraction, just like a CRC. Finally the 15 bits are XORed
with the fixed mask 101010000010010.
Example: level M, mask 5 (the standard's own example)
Data bits: level M = 00, mask 5 = 101 → 00101
Shift left by 10: 001010000000000
XOR generator, aligned under the top 1: 10100110111
---------------
Remainder (last 10 bits): 0011011100
Data + remainder: 001010011011100
XOR with 101010000010010: 100000011001110
Our example: level M, mask 0
Data bits 00000 → remainder 0000000000 → 000000000000000 XOR with 101010000010010: 101010000010010
The second example shows why the final XOR exists: without it, level M with mask 0 would produce fifteen zeros, an all-light strip that is indistinguishable from a blank, damaged or missing format area. The fixed XOR guarantees every combination contains some dark modules.
There are only 32 possible format words, and any two of them differ in at least 7 bits. So a decoder can simply compare what it reads against all 32 and take the closest; it can fix up to 3 wrong bits. And because the information is written twice, it can try the other copy if one is too damaged.
Bit 14 (the most significant) starts in the left column of row 8. The first copy runs along row 8, skipping the timing module at column 6, then up column 8 past the timing module at row 6. The second copy is split: bits 14 down to 8 climb column 8 under the bottom-left finder, bits 7 down to 0 run along row 8 under the top-right finder. The red D is the always-dark module, sitting just above the bottom-left copy.
Version Information
From version 7 upward, modules get small enough and symbols big enough that counting the timing pattern is error-prone, so the version is written explicitly: 6 bits for the version number plus 12 check bits, from an (18, 6) code that the standard calls a Golay code (you'll often see it described as BCH(18, 6)). The generator is
That's 1111100100101 in binary. Version 7 is 000111; shifting and dividing gives the remainder 110010010100, so the full word
is 000111110010010100. There's no XOR mask this time: the version is never below 7, so the data
bits can never all be zero. The 34 valid words differ pairwise in at least 8 bits, so up to 3
errors can be corrected.
The 18 bits fill two 6 × 3 blocks, one above the bottom-left finder and one left of the top-right finder, the second the transpose of the first:
The Whole Encoder in Pseudocode
function makeQR(text, ecLevel):
mode ← mostCompactMode(text) # numeric ⊂ alnum ⊂ byte
version ← smallest v such that bitsNeeded(text, mode, v) ≤ dataCodewords(v, ecLevel) × 8
bits ← modeIndicator(mode) + count(text, mode, version) + encode(text, mode)
bits += "0" × min(4, capacityBits − len(bits)) # terminator
bits += "0" × ((8 − len(bits) mod 8) mod 8) # byte boundary
bytes ← toBytes(bits)
alternate 0xEC, 0x11 onto bytes until full
blocks ← split(bytes, version, ecLevel) # group 1 + group 2
for each block: block.ec ← rsRemainder(block.data, ecPerBlock) # GF(256), poly 0x11D
final ← interleave(all data) + interleave(all ec) + remainderBits(version)
grid ← drawFunctionPatterns(version) # finders, separators, timing,
# alignment, dark module, reserved areas
placeZigzag(grid, final)
best ← argmin over mask in 0..7 of
penalty(withFormat(applyMask(grid, mask), ecLevel, mask))
return withVersionInfo(withFormat(applyMask(grid, best), ecLevel, best), version)</pre>
Reading It Back
A scanner runs the pipeline backwards, and you can now name every step:
- Find the three finders by hunting for 1 : 1 : 3 : 1 : 1 runs, which gives position, rotation and approximate module size.
- Lay a grid over the image using the timing patterns and, for version 2 and up, the alignment patterns to correct for perspective.
- Read the format information from either copy and snap it to the nearest of the 32 valid words. Now it knows the EC level and the mask. For version 7 and up, read the version information the same way.
- Unmask the encoding region by XORing the same mask again.
- Walk the zigzag to recover the codeword sequence, then de-interleave it into blocks.
- Reed-Solomon decode each block: syndromes, error locator, error values, exactly as in the Reed-Solomon article.
- Parse the segments: mode indicator, count, characters, until the terminator.
This is why a QR code shrugs off so much abuse. Destroy a few codewords' worth of modules anywhere in the data region and the RS layer quietly repairs them. That's also how "logo in the middle" QR codes work: the designer deliberately destroys some modules, usually at level H, and spends part of the error-correction budget to buy a pretty picture. Damage the finders, the timing patterns or both copies of the format information, however, and the scanner never gets far enough to try.
Wrapping Up
A QR code packs almost every idea from this series into a square you can print on a coffee cup. Mode selection is plain compression. Reed-Solomon over GF(256) does the heavy lifting on the data, interleaving spreads physical damage evenly across blocks, BCH codes guard the header, and a layer of purely practical engineering (the 1 : 1 : 3 : 1 : 1 finder ratio, the timing lines, the zigzag and the masks) makes sure a cheap phone camera can find the grid in the first place.
The same toolbox shows up in QR's relatives. Micro QR, defined in the same standard, keeps a single finder pattern for very small symbols. Data Matrix (with its L-shaped border) and Aztec (with its bullseye centre) choose different finder shapes, but both lean on Reed-Solomon codes underneath. Once you've built one of these by hand, the others are variations on a theme.
Key Takeaways
- A QR code is a grid of 17 + 4v modules per side, from version 1 (21 × 21) to version 40 (177 × 177).
- Function patterns (finders, separators, timing, alignment, dark module) exist only to help the scanner locate and measure the grid; everything else holds codewords.
- Text is encoded in numeric, alphanumeric, byte or kanji mode, each with a 4-bit mode indicator and a version-dependent character count, then terminated and padded with
0xEC/0x11to the exact capacity. - Error correction is Reed-Solomon over GF(256) (polynomial
0x11D, roots α⁰…αⁿ⁻¹), in one or more blocks that are interleaved so localised damage is shared out. - Bits are placed in a two-column zigzag from the bottom-right, skipping function patterns and the timing column.
- One of eight masks is XORed over the data, chosen by four penalty rules that punish runs, blocks, false finders and imbalance.
- The format information (level + mask) uses BCH(15, 5) plus the XOR mask
101010000010010, written twice; version information (v7+) uses an (18, 6) code, also written twice.