How Barcodes and QR Codes Encode Information
Laser time-ratio guard bars, 1:1:3:1:1 perspective finder patterns, XOR data masking, and Reed-Solomon error correction over GF(2^8)
“How do black-and-white stripes and pixel grids store numbers and URLs—and how can a smartphone decode a QR code even when it is tilted, upside-down, or 30% destroyed?”
A 1D supermarket barcode encodes 12 digits in the relative widths of 95 black-and-white modules verified by a Modulo-10 check digit. A 2D QR code expands into a two-dimensional binary matrix anchored by three 1:1:3:1:1 finder squares for 360-degree perspective homography, XOR data masks to prevent blank regions, and Galois Field GF(2^8) Reed-Solomon polynomials that mathematically reconstruct up to 30% missing data.
- How does a 1D supermarket barcode (UPC-A) represent digits using black bars and white spaces?
- How does a barcode scanner read a label upside-down or at different swipe speeds?
- Why do QR codes have three large squares in the corners instead of four?
- What is the 1:1:3:1:1 Finder Pattern ratio and how does it enable 360-degree camera alignment?
- How does Reed-Solomon error correction allow a QR code to work with a logo in the middle or 30% damage?
- Why do QR codes apply an XOR mask before printing?
To build a complete first-principles mental model of this mechanism, we recommend starting with these foundational explainers:
Quick answer
Barcodes and QR codes are optical translations of binary numbers (1 and 0) designed so machines can read physical objects without human typing errors:
- 1D Linear Barcodes (UPC-A / EAN-13): Invented by Norman Woodland and Bernard Silver and standardized by George Laurer at IBM in 1973, a supermarket barcode slices a horizontal strip into 95 equal-width binary modules. Each of the 12 decimal digits is encoded as a 7-module pattern consisting of two black bars (
1) and two white spaces (0). A laser scanner measures the time duration ratios of the reflected light pulses relative to the narrow101guard bars at the edges, and verifies the read using a Modulo-10 Check Digit. - 2D Matrix Codes (QR Codes, ISO/IEC 18004): Invented in 1994 by Masahiro Hara at Denso Wave to track automobile components at high speed, a Quick Response (QR) code encodes data across both horizontal and vertical dimensions (21 × 21 up to 177 × 177 modules), expanding capacity from 12 digits to 4,296 alphanumeric characters (or 2,953 raw bytes).
- 360-Degree Geometric Alignment: Three corners contain large 7 × 7 Finder Patterns whose black-and-white cross-section is always 1 : 1 : 3 : 1 : 1 regardless of rotation angle. Leaving the fourth corner empty tells the camera which way is "up," while timing lines and alignment squares let the smartphone un-tilt (homography warp) the image in milliseconds.
- XOR Masking & Reed–Solomon Algebra: Before printing, the payload is XORed with one of 8 mathematical checkerboard masks so no large blank patches can confuse the camera. Finally, Reed–Solomon error-correcting polynomials over the finite Galois Field GF(28) append parity bytes that can mathematically reconstruct the original data even if up to 30% of the QR code is torn away or covered by a logo.
1. How a 1D Supermarket Barcode (UPC-A) Encodes 12 Digits
Look closely at the barcode on a cereal box or bottle of water. You might assume that thin bars mean 0 and thick bars mean 1, or that the black bars alone carry the information while the white gaps are just background spacing.
Both assumptions are wrong. In a standard UPC-A (Universal Product Code) barcode, white spaces and black bars are equally important.
The 95-Module Grid
Every UPC-A barcode—whether printed tiny on a pack of chewing gum or huge on a shipping crate—is divided horizontally into exactly 95 identical unit widths called modules (where a black module is 1 and a white module is 0):
ANATOMY OF A 95-MODULE 1D UPC-A BARCODE
Quiet Start Left 6 Digits Center Right 6 Digits End Quiet
Zone Guard (Odd Parity: 0...1) Guard (Even Parity: 1...0) Guard Zone
(9 mod) (3 mod) 6 × 7 = 42 modules (5 mod) 6 × 7 = 42 modules (3 mod)(9 mod)
┌──────┬───────┬────────────────────────────┬────────┬────────────────────────────┬───────┬──────┐
│000000│ 1 0 1 │ [D1][D2][D3][D4][D5][D6] │0 1 0 1 0│ [D7][D8][D9][D10][D11][C] │ 1 0 1 │000000│
└──────┴───────┴────────────────────────────┴────────┴────────────────────────────┴───────┴──────┘
▲
Modulo-10 Check Digit (d₁₂)
- Start and End Guards (
101, 3 modules each): Two 1-module-wide black bars separated by a 1-module white space. These act as the optical clock crystal for the scanner: by timing how many microseconds the laser beam takes to cross those narrow101bars, the scanner calibrates the exact swipe speed! - Center Guard (
01010, 5 modules): Splits the barcode into a 6-digit Left Half (Number System + Manufacturer ID) and a 6-digit Right Half (Product ID + Check Digit). - 7-Module Digit Encoding (2 Bars + 2 Spaces): Every decimal digit (0–9) occupies 7 modules, always partitioned into two white spaces and two black bars whose individual widths range from 1 to 4 modules.
| Decimal Digit | Left-Side Pattern (L-Code, Odd Parity) | Right-Side Pattern (R-Code, Bitwise Complement, Even Parity) | Bar/Space Width Ratio |
|---|---|---|---|
0 | 0001101 (three 1s) | 1110010 (four 1s) | 3 − 2 − 1 − 1 |
1 | 0011001 (three 1s) | 1100110 (four 1s) | 2 − 2 − 2 − 1 |
2 | 0010011 (three 1s) | 1101100 (four 1s) | 2 − 1 − 2 − 2 |
3 | 0111101 (five 1s) | 1000010 (two 1s) | 1 − 4 − 1 − 1 |
4 | 0100011 (three 1s) | 1011100 (four 1s) | 1 − 1 − 3 − 2 |
5 | 0110001 (three 1s) | 1001110 (four 1s) | 1 − 2 − 3 − 1 |
How the Scanner Knows If the Box Is Upside-Down
Notice a clever symmetry in the table above:
- Every Left-Side digit (
L-Code) starts with a0(white space), ends with a1(black bar), and contains an odd number of black modules (3 or 5). - Every Right-Side digit (
R-Code) is the exact bitwise NOT of the left code (0↔1): it starts with a1, ends with a0, and contains an even number of black modules (2 or 4).
When a cashier drags a cereal box across the glass scanner upside-down, the laser sweeps from right to left. The decoder immediately sees even-parity digits first instead of odd-parity digits! Without missing a beat, the firmware reverses the bit array in memory and decodes the 12 digits in the proper order.
The Modulo-10 Check Digit Equation
Before the scanner emits its familiar "beep!", it must verify that a water droplet or wrinkle on the wrapper did not misread a digit. The 12th digit (d12) is a mathematical checksum computed from the first 11 digits:
Because gcd(3, 10) = 1, multiplying all odd-positioned digits by 3 and adding the even-positioned digits guarantees that 100% of single-digit errors (and ~89% of adjacent transposition errors) fail the Modulo-10 check. If the sum does not end in 0, the scanner stays silent and waits for the next sweep of the laser mirror (which scans the label 500–1,000 times per second).
1D Linear Barcode (UPC-A / EAN-13)
Encodes information strictly along the horizontal axis (X); vertical height exists only to make laser alignment easier | Stores 12 to 13 numeric digits (95 binary modules); requires an external database lookup to resolve product details | Scanned along a 1D line by a photodiode laser or linear CCD; scratches perpendicular to bars can sever the entire symbol | Uses a single Modulo-10 check digit: detects read errors (preventing wrong prices) but cannot reconstruct missing digits
2D Matrix Code (QR Code, ISO/IEC 18004)
Encodes information across both horizontal (X) and vertical (Y) grid coordinates (21x21 up to 177x177 modules) | Stores up to 7,089 numeric digits, 4,296 alphanumeric characters, or 2,953 binary bytes directly inside the symbol | Captured by a 2D CMOS camera sensor from any 360° rotation or steep 3D tilt via three 1:1:3:1:1 corner finder patterns | Uses Reed-Solomon polynomial error correction over GF(2^8): mathematically reconstructs up to 30% missing or destroyed modules
2. Why QR Codes Were Invented: From Auto Factories to Global Payments
By the early 1990s, Toyota's manufacturing plants in Japan faced a bottleneck. A single Kanban parts bin often carried ten separate 1D barcodes side by side—one for the part number, one for the lot number, one for the quantity, and one for the destination assembly line. Factory workers had to scan ten barcodes on every box by hand, thousands of times a shift.
In 1994, Masahiro Hara and a two-person engineering team at Denso Wave set out to design a two-dimensional code that could hold hundreds of characters and be decoded ten times faster than existing 2D symbols.
The hardest engineering problem was not storing bits in a grid—it was finding the grid instantly on a cluttered factory box covered in text, diagrams, and oil smudges.
Hara found the solution during a lunchtime game of Go: looking at the black and white stones arranged on the 19 × 19 grid, he realized that a geometric target with a unique, unmistakable spatial frequency could let a camera lock onto the code before even decoding a single data bit.
3. Spatial Anatomy of a QR Code: The 1:1:3:1:1 Finder Ratio
Every standard QR code ranges from Version 1 (21 × 21 modules) up to Version 40 (177 × 177 modules), growing by 4 modules per side with each version (N = 17 + 4V).
Before a single byte of your URL or UPI payment string (see How UPI Works) is placed into the matrix, the encoder reserves fixed Function Patterns that guide the camera's computer-vision pipeline:
ANATOMY OF A VERSION 1 (21×21) QR CODE MATRIX
Col 0 Col 6 Col 14 Col 20
▼ ▼ ▼ ▼
┌──────────────┬─┬───────────┬──────────────┐
│ ████████████ │ │ ░░░░░░░░░ │ ████████████ │ ◄── Top-Left & Top-Right
│ ██ ██ │ │ ░░░░░░░░░ │ ██ ██ │ 7×7 Finder Patterns
│ ██ ████ ██ │ │ ░░ Data ░░│ ██ ████ ██ │ (Ratio 1:1:3:1:1)
│ ██ ████ ██ │ │ ░░░░░░░░░ │ ██ ████ ██ │
│ ██ ██ │ │ ░░░░░░░░░ │ ██ ██ │
│ ████████████ │ │ ░░░░░░░░░ │ ████████████ │
├──────────────┼─┼───────────┼──────────────┤
Row 6 │ 1 0 1 0 1 0 │1│ 0 1 0 1 0 │ 15-Bit Format│ ◄── Row 6 Timing Pattern
├──────────────┼─┼───────────┴──────────────┤
│ 15-Bit Format│0│ ░░░░░░░░░░░░░░░░░░░░░░░░ │
│ Info Header │1│ ░░░░░░░ Payload & ░░░░░░ │ ◄── Boustrophedon 2-Col
│ (ECC + Mask) │0│ ░░░░ Reed-Solomon ECC ░░ │ Up/Down Byte Snake
├──────────────┼─┤ ░░░░░░░░░░░░░░░░░░░░░░░░ │ ▲ │
│ ████████████ │1│ ░░░░░░░░░░░░░░░░░░░░░░░░ │ │ ▼
│ ██ ██ │0│ ░░░░░░░░░░░░░░░░░░░░░░░░ │ Starts at Bottom-Right!
│ ██ ████ ██ │1│ ░░░░░░░░░░░░░░░░░░░░░░░░ │
│ ██ ██ │0│ ░░░░░░░░░░░░░░░░░░░░░░░░ │ ◄── NO Finder Pattern at
│ ████████████ │1│ ░░░░░░░░░░░░░░░░░░░░░░░░ │ Bottom-Right (Defines Up!)
└──────────────┴─┴──────────────────────────┘
1. Why Three Corners Have Squares (and the Fourth Does Not)
A QR code places a 7 × 7 Finder Pattern (surrounded by a 1-module white separator) at the Top-Left, Top-Right, and Bottom-Left corners—leaving the Bottom-Right corner without a finder square.
- With three points forming a right-angled L-triangle, the smartphone camera immediately knows the exact 360∘ rotation angle of the code (0∘, 90∘, 180∘, or 270∘): whichever corner has two neighbors at 90∘ is always the Top-Left origin (0,0)!
- Why the 1 : 1 : 3 : 1 : 1 cross-section? A Finder Pattern consists of a 3 × 3 solid black center inside a 5 × 5 white ring inside a 7 × 7 black outer ring. If a camera scanline slices through the center of a Finder Pattern—horizontally, vertically, or even diagonally at 45∘—the ratio of module widths (Black : White : Black : White : Black) is always 1 : 1 : 3 : 1 : 1! Masahiro Hara's team surveyed thousands of printed magazines, shipping labels, and kanji characters and discovered that the 1:1:3:1:1 thickness ratio almost never occurs in human typography.
2. Timing Patterns and Perspective Homography
- Timing Patterns: Row 6 and Column 6 contain a strict alternating
1010101...dotted line connecting the Finder Patterns, allowing the decoder to count module pitch even if the sticker is wrapped around a curved coffee cup. - Alignment Patterns (Version 2+): Larger QR codes embed smaller 5 × 5 bullseye squares (1:1:1:1:1 ratio) inside the lower-right quadrant and across the interior. Using the centers of the Finder and Alignment patterns, the camera solves a 3 × 3 projective homography matrix, mathematically flattening a tilted 3D photograph back into an orthogonal 2D square grid.
3. The 15-Bit Format Information Strip
Before the decoder can read the payload, it must know two critical parameters: which Error Correction Level (L, M, Q, H) was used and which of the 8 XOR Masks (000–111) was applied.
- These 5 data bits (2 bits for ECC + 3 bits for Mask ID) are protected by a 10-bit Bose–Chaudhuri–Hocquenghem BCH(15, 5) error-correcting code and XORed with
101010000010010. - The resulting 15-bit Format String is written twice—once around the Top-Left Finder Pattern, and once split between the Top-Right and Bottom-Left Finder Patterns—guaranteeing the header survives even if an entire corner of the QR code is ripped off!
4. Bitstream Encoding, Boustrophedon Placement, and XOR Masking
Once the function patterns are reserved, how does a string like https://thisishowitworks.in turn into black and white squares?
Step 1: Mode Selection and Bit Packing
To pack as much text as possible into the smallest grid, the QR standard defines four primary encoding modes, declared by a 4-bit Mode Indicator at the very start of the bitstream:
- Numeric Mode (
0001): Packs triplets of decimal digits (000–999) into 10 bits (3.33 bits/digit instead of 8 bits). - Alphanumeric Mode (
0010): Packs pairs of uppercase characters (0–9, A–Z, $, %, *, +, -, ., /, :) into 11 bits (45 × C1 + C2, or 5.5 bits/char). - Byte Mode (
0100): Encodes full ISO-8859-1 or UTF-8 bytes at 8 bits per byte (used for lowercase URLs and emojis). - Kanji Mode (
1000): Packs 2-byte Shift-JIS characters into 13 bits.
After the 4-bit Mode Indicator and Character Count header, the message bits are appended, followed by a 0000 terminator and alternating pad bytes (11101100 = 0xEC and 00010001 = 0x11) to fill the exact data capacity of that QR version.
Step 2: The Boustrophedon ("Ox-Plowing") Zig-Zag
Where do the bytes go? Starting at the bottom-right corner, the encoder places each 8-bit byte into a 2-module-wide vertical column:
- It places the Most Significant Bit (MSB) at the bottom-right, then zig-zags right-to-left, upward all the way to the top of the grid.
- At the top, it shifts 2 modules to the left and zig-zags downward to the bottom, plowing back and forth across the matrix (a pattern sharing its name with ancient boustrophedon inscriptions; see How Was Writing Invented From Scratch?) while stepping cleanly around Finder, Alignment, and Timing patterns.
Step 3: Why Every QR Code Must Be XOR-Masked
Imagine encoding a payload containing dozens of zero bytes (00000000). If printed directly, the QR code would have a massive white hole in the middle, making it impossible for the camera to track module grid spacing. Worse, random data bits might accidentally form a 1:1:3:1:1 pattern inside the payload, tricking the camera into seeing a fourth Finder Pattern!
To prevent this, ISO/IEC 18004 defines 8 mathematical mask formulas over row i and column j:
- Mask
000: Flip module (i, j) if (i + j) mod 2 = 0 (a classic checkerboard) - Mask
001: Flip module (i, j) if i mod 2 = 0 (horizontal stripes) - Mask
010: Flip module (i, j) if j mod 3 = 0 (vertical stripes) - Mask
011: Flip module (i, j) if (i + j) mod 3 = 0 (diagonal stripes) - (Plus four nonlinear combinations
100through111)
The encoder applies each of the 8 masks via bitwise XOR (⊕) to the data and ECC area, evaluates four Penalty Rules (penalizing runs of ≥ 5 identical modules, 2× 2 solid blocks, false 1:1:3:1:1 finder sequences, and dark/light imbalance away from 50%), and outputs whichever mask achieves the lowest penalty score.
5. The Crown Jewel: Reed–Solomon Error Correction Over GF(28)
You have probably seen artistic QR codes with a brand logo or coffee shop icon pasted directly over the middle of the grid—and yet your phone scans them in a fraction of a second. How can you delete 25% of a binary message and still recover 100% of the original bytes without guessing?
The answer is Reed–Solomon Error Correction, invented in 1960 by Irving Reed and Gustave Solomon at MIT Lincoln Laboratory (and also used on the Voyager deep-space probes, CDs/DVDs, and 5G cellular links).
How Polynomial Oversampling Works Intuitively
Think back to high-school algebra:
- Two points uniquely determine a straight line (y = ax + b).
- If you plot k = 2 data points on that line, and then evaluate the same line at 2t = 4 additional x-coordinates, you now have n = 6 points that all lie on one unique line.
- Even if a coffee stain completely destroys any 2 of those points (or corrupts 2 of them into wrong values), the remaining points still uniquely identify the original line y = ax + b!
Galois Field GF(28) Byte Arithmetic
In a computer, if you multiply 8-bit integers using ordinary arithmetic, numbers quickly overflow past 255. Reed–Solomon avoids overflow by performing all addition and multiplication inside a finite Galois Field of 256 elements, GF(28):
- Every 8-bit byte (0 to 255) is treated as a 7th-degree binary polynomial b7 x7 + b6 x6 + … + b1 x + b0.
- Addition in GF(28) is simply bitwise XOR (⊕) with no carries (a + b = a ⊕ b).
- Multiplication in GF(28) is polynomial multiplication modulo the irreducible primitive polynomial specified by ISO/IEC 18004:
To generate 2t error-correction parity bytes for k data bytes, the encoder constructs a message polynomial M(x) and computes the polynomial remainder when M(x) · x2t is divided by the Reed–Solomon generator polynomial:
where α = 2 is the primitive element of GF(28). By the algebraic Singleton Bound, appending 2t Reed–Solomon parity bytes allows the receiver's Berlekamp–Massey and Forney syndrome decoder to simultaneously locate and correct up to t completely unknown corrupted bytes anywhere in the block!
| QR Error Correction Level | Format Bits | Max Recoverable Byte Damage (t / n) | Typical Engineering Use Case |
|---|---|---|---|
| Level L (Low) | 01 | ∼ 7% of codewords | Clean digital screens, dense high-capacity URLs |
| Level M (Medium) | 00 | ∼ 15% of codewords | Standard retail packaging, UPI merchant standees |
| Level Q (Quartile) | 11 | ∼ 25% of codewords | Industrial factory bins exposed to grease and dust |
| Level H (High) | 10 | ∼ 30% of codewords | Outdoor signs and QR codes with a center brand logo |
Wait—why does pasting a logo in the center of a QR code work? The QR code standard does not have a special "logo zone." When a designer places a logo over the center of a Level H QR code, they are intentionally destroying ~20% of the data modules! When your smartphone scans the code, the Reed–Solomon decoder treats the entire logo as a burst of corrupted bytes and mathematically solves the system of GF(28) syndrome equations to reconstruct the missing modules underneath the logo.
Camera converts grayscale frame into a binary black/white image using local luminance windows to reject shadows1:1:3:1:1 Finder Lock :: Scanline detector locates the three 7x7 corner targets and 5x5 alignment anchor to establish 360° orientationHomography Unwarping :: 3x3 projective transformation matrix un-tilts the 3D perspective into an exact N x N module coordinate gridBCH Format & XOR Unmask :: Decoder reads the 15-bit BCH header, identifies the 3-bit mask ID, and XORs the matrix to remove the checkerboard maskGF(2^8) Reed-Solomon ECC :: Syndrome calculator, Berlekamp-Massey locator, and Forney evaluator repair up to 30% smudged or logo-covered bytesBitstream Mode Unpacking :: Parser reads the 4-bit Mode Indicator (Numeric/Alphanumeric/Byte) and reconstructs the UTF-8 URL or payment URI
Why this matters
Every day, billions of packages, boarding passes, and instant bank payments (explored in How UPI Works and How UPI Works Without Internet) bridge the physical world and the digital network through printed ink. When you point your smartphone camera at a paper QR standee and tap the screen (using the capacitive grid detailed in How Touchscreens Detect Your Finger), your device executes projective geometry, finite-field abstract algebra over GF(28), and bitwise cryptography in under 50 milliseconds—turning a smudged square of cardboard into an error-free digital transaction.
How Digital Payments and Banking Infrastructure Work
Starting question: “When you tap a credit card or scan a UPI QR code and see "Payment Successful" in under two seconds, what messages actually travel across banking switches—and when does real money move between banks?”
Explains how 1:1:3:1:1 finder patterns and GF(2^8) Reed-Solomon error correction encode merchant VPA payloads onto counter stickers.
Where to Go From Here
Follow downstream mechanisms, contrasting architectures, or applications of these principles.
How Elevators Safely Lift and Stop Passengers Without Falling: Traction, Governors, and Rail Safeties
What prevents a multi-ton elevator car hanging hundreds of meters in the air from plunging down the hoistway if its cables snap, and how does traction friction lift passengers without slipping?
How Microwave Ovens Heat Food and Why Metal Sparks: Magnetrons, Dielectric Losses, and Plasma Physics
How does a metal box use radar technology to boil a cup of tea without heating the air inside, why does it notoriously heat hot pockets unevenly, and what causes a forgotten metal fork to violently erupt in sparks and plasma?
How Noise-Cancelling Headphones Silence the World
Why can active noise-cancelling headphones completely erase the deafening roar of a jet engine, but still let you hear someone speaking right next to you?
How Smoke Detectors Detect Invisible Fire
How does a smoke alarm use radioactive alpha particles or infrared light scattering to detect microscopic combustion products before flames appear?
Verified Specifications & Architectural References
This explainer is grounded in primary-source engineering specifications, regulatory circulars, and standard documentation.
ISO/IEC 18004: Information technology — Automatic identification and data capture techniques — QR Code bar code symbology specification
The global engineering specification defining QR code versions 1–40, finder/alignment patterns, BCH format headers, XOR masking penalties, and GF(2^8) Reed-Solomon generator polynomials.
GS1 General Specifications — EAN/UPC Symbology
The authoritative technical standard governing 1D UPC-A and EAN-13 module geometry, left/right odd-even parity tables, and Modulo-10 check digit arithmetic.
Polynomial Codes Over Certain Finite Fields
Irving Reed and Gustave Solomon's foundational mathematical paper introducing finite-field polynomial error-correcting codes.