← Knowledge Base
Deep Dive — Scanning Technology

Codes & Scanning

From the first laser-scanned pack of Wrigley's gum in 1974 to the billions of QR codes scanned daily, this is the complete story of how machines read visual patterns to move data at the speed of light.

1948
First barcode patent
7,089
Max QR numeric chars
30%
Max error recovery
6B+
Barcodes scanned daily

History of Barcodes

From beach sand drawings to the beep heard around the world.

The story begins in 1948 on a beach in Miami. Bernard Silver, a graduate student at Drexel Institute of Technology, overheard a supermarket executive pleading with a dean to develop a system for automatically reading product information at checkout. Silver told his friend Norman Joseph Woodland, and the two began experimenting.

Woodland, inspired by Morse code, dragged his fingers through the sand to create extended dots and dashes. The result was a bullseye pattern of concentric circles — the first barcode concept. On October 7, 1952, they received US Patent 2,612,994 for their "Classifying Apparatus and Method."

The Bullseye Design

Woodland's original patent used circular rings, not straight lines. The advantage was omnidirectional scanning — the code could be read from any angle. It was decades ahead of the technology needed to read it.

The Long Wait

The patent expired in 1969 without commercial success. The technology to read barcodes — affordable lasers and microprocessors — simply didn't exist yet. Through the 1960s, railroads experimented with colored stripes on freight cars (KarTrak system), but it was unreliable in dirty conditions.

In 1971, George Laurer at IBM developed the Universal Product Code (UPC), switching from Woodland's circles to the familiar vertical lines. The linear design was easier to print with existing press technology and cheaper to scan with a single laser line.

The First Scan

On June 26, 1974, at a Marsh Supermarket in Troy, Ohio, cashier Sharon Buchanan scanned a 10-pack of Wrigley's Juicy Fruit chewing gum. The item was chosen deliberately — executives thought a small item would demonstrate that even tiny packages could carry barcodes. The price: 67 cents.

The Beep Heard Around the World

That pack of gum is now preserved in the Smithsonian Institution's National Museum of American History. The single scan launched a revolution that would transform global retail, logistics, healthcare, and virtually every industry that moves physical goods.

The Retail Revolution

Adoption was slow at first. Stores needed to invest in scanners, and manufacturers needed to print codes on every package. By 1984, only 33% of grocery stores had scanners. But the benefits were undeniable: faster checkout (up to 40% faster), accurate pricing, and for the first time, real-time inventory data. By the 1990s, barcodes were essentially universal. Today, over 6 billion barcodes are scanned every single day worldwide.

How 1D Barcodes Work

Encoding data in the widths of bars and the spaces between them.

A 1D (linear) barcode encodes data using a series of parallel lines of varying widths, separated by spaces of varying widths. The scanner reads the relative widths of these bars and spaces to decode the information. A "thin" element typically represents a binary 0, and a "thick" element represents a 1 — though the actual encoding varies by symbology.

How Laser Scanning Works

A laser scanner emits a thin beam of red light (typically 650nm wavelength) that sweeps across the barcode using an oscillating mirror. Dark bars absorb the light, while white spaces reflect it back to a photodiode detector. The detector converts the pattern of reflections into an electrical signal — essentially a series of high and low voltages — which a decoder chip translates into the encoded number.

UPC-A Structure

The Universal Product Code (UPC-A) is the most common barcode in North American retail. It encodes exactly 12 numeric digits:

UPC-A: 0 36000 29145 2 Position breakdown: 0 — Number system digit (0 = standard UPC item) 36000 — Manufacturer code (Procter & Gamble) 29145 — Product code (specific product) 2 — Check digit (calculated from other 11) Number System values: 0, 1, 6, 7, 8 — Regular UPC codes 2 — Variable weight items (deli, produce) 3 — Pharmaceuticals (National Drug Code) 4 — In-store use (loyalty cards, etc.) 5, 9 — Coupons

Check Digit Calculation

The check digit prevents scanning errors. For UPC-A, the algorithm is:

UPC-A Check Digit Algorithm

Step 1: Add all digits in odd positions (1st, 3rd, 5th, 7th, 9th, 11th) and multiply by 3.
Step 2: Add all digits in even positions (2nd, 4th, 6th, 8th, 10th).
Step 3: Sum the results from Step 1 and Step 2.
Step 4: The check digit is (10 - (sum mod 10)) mod 10.

Example: 0 3600 02914 5 ? Odd positions: 0 + 6 + 0 + 0 + 9 + 4 = 19 × 3 = 57 Even positions: 3 + 0 + 0 + 2 + 1 + 5 = 11 Sum: 57 + 11 = 68 Check: (10 - (68 mod 10)) mod 10 = (10 - 8) mod 10 = 2

Common 1D Barcode Symbologies

SymbologyCharactersLengthPrimary UseDensity
UPC-ANumeric (0-9)12 digits fixedNorth American retailMedium
EAN-13Numeric (0-9)13 digits fixedInternational retailMedium
Code 128Full ASCII (128 chars)VariableShipping, logisticsVery High
Code 39A-Z, 0-9, symbolsVariableMilitary, healthcareLow
Interleaved 2 of 5Numeric (0-9)Variable (even)Warehouse, distributionHigh
Codabar0-9, - $ : / . +VariableLibraries, blood banksLow

EAN-13 (European Article Number) is the international superset of UPC-A. A UPC-A code is simply an EAN-13 with a leading zero. The first 2-3 digits represent the country of the issuing GS1 authority (not necessarily where the product was made). Code 128 is the workhorse of logistics — it can encode the full ASCII character set with very high density, making it ideal for shipping labels. Code 39 is self-checking (no check digit required) and was the first alphanumeric symbology widely adopted, especially in U.S. Department of Defense applications.

Barcode Anatomy

Every zone and bar in a UPC serves a specific purpose.

Complete UPC-A Barcode Structure ┌───────────────────────────────────────────────────────────────────┐ │ Quiet │ Start │ Left digits │ Center │ Right digits │ End │ Quiet │ │ Zone │ Guard │ (6 digits) │ Guard │ (6 digits) │ Guard│ Zone │ │ │ 101 │ │ 01010 │ │ 101 │ │ └───────────────────────────────────────────────────────────────────┘ Quiet Zones: Minimum 9 modules (white space) on each side. Tells the scanner "the barcode starts/ends here." Start/End Guards: Pattern 101 (bar-space-bar). Fixed reference patterns for the decoder. Center Guard: Pattern 01010 (space-bar-space-bar-space). Separates left and right halves; provides a mid-scan calibration point. Data Characters: Each digit encoded as 7 modules (bars + spaces). Left side uses "odd parity" encoding; right side uses "even parity." This left/right distinction lets the scanner read in either direction.

How a Scanner Reads the Code

The scanning process is direction-independent. When the scanner encounters the barcode:

1. Detect the quiet zone (continuous white space) → 2. Recognize the start guard pattern (101) → 3. Read 6 data characters (each is 7 modules wide, composed of 2 bars and 2 spaces) → 4. Recognize the center guard pattern (01010) → 5. Read 6 more data characters → 6. Recognize the end guard pattern (101) → 7. Verify check digit → 8. If reading was right-to-left, reverse the result.

The scanner measures the relative widths of bars and spaces, not absolute widths. This means a barcode printed at different sizes will still scan correctly, as long as the ratios between elements are preserved and the minimum module size is maintained. Each data character is exactly 7 modules wide, consisting of two bars and two spaces. The narrow-to-wide ratio is what carries the encoded digit.

Why Barcodes Are Tall

The height of a barcode is redundant — every horizontal slice contains the same data. The height exists so that a sweeping laser line, which crosses at various angles, will always find a horizontal path through the bars. Taller barcodes are more tolerant of scanner misalignment.

Scanning Technology

From sweeping lasers to 2D imagers: the evolution of barcode readers.

L Laser Scanners

A focused laser beam bounces off an oscillating mirror, sweeping a red line across the barcode. A single photodiode measures the intensity of reflected light. Fast, inexpensive, and reliable for 1D codes. The dominant technology from the 1970s through the 2000s.

C CCD Scanners

Uses a row of tiny light sensors (a linear CCD array) to capture the entire barcode at once, like a single-line camera. No moving parts. Requires the barcode to be close to the scanner. Common in budget handheld scanners and fixed-mount retail applications.

I 2D Area Imagers

Essentially a small camera that captures a full 2D image, then processes it with software to find and decode any barcode type — 1D or 2D. Can read QR codes, Data Matrix, damaged codes, and even codes on screens. The modern standard.

P Camera-Based (Phone)

Smartphone cameras combined with software decoding. Uses autofocus, image stabilization, and computational algorithms. Slower than dedicated scanners but universally available. Modern phones can decode in under 100ms thanks to neural-network-assisted pattern recognition.

Scanner Comparison

FeatureLaserCCD2D Imager
1D BarcodesExcellentGoodExcellent
2D Codes (QR)NoNoYes
Read DistanceUp to 10m+1-10 cmUp to 15m
SpeedVery fastFastFast
Screen ReadingNoSometimesYes
Moving PartsYes (mirror)NoNo
Damaged CodesPoorPoorGood
CostLow-MediumLowMedium-High

The industry has decisively shifted to 2D imagers. The reason is simple: one scanner handles everything. Retailers need to scan traditional UPC barcodes, QR codes on mobile coupons, 2D codes on driver's licenses for age verification, and codes displayed on phone screens. Laser scanners, despite their speed advantage, simply cannot read 2D codes or screens. The falling cost of CMOS image sensors has made the price gap negligible.

QR Code History

Born in a Toyota factory, adopted by the world.

In 1994, Masahiro Hara and his team at Denso Wave (a subsidiary of Toyota) created the QR code to solve a specific problem: tracking car components through the manufacturing process. Existing 1D barcodes could only hold about 20 characters — far too little for the part numbers, batch information, and production data Toyota needed.

The name "QR" stands for "Quick Response" — the code was designed to be decoded rapidly by scanners on high-speed production lines. Hara's team studied how existing codes failed and designed the three distinctive finder patterns (the large squares in three corners) to allow instant detection of the code's position and orientation, regardless of angle.

The Key Decision: Open Standard

Denso Wave made the pivotal decision to not exercise their patent rights. Anyone could create or read QR codes without paying licensing fees. This single decision is arguably why QR codes, rather than competing formats, became the global standard. The specification was released as ISO/IEC 18004.

Timeline of Adoption

1994 — QR code invented at Denso Wave
1997 — Approved as AIM standard
2000 — Approved as ISO/IEC 18004
2002 — Camera phones with QR readers launch in Japan
2010s — Marketing adoption (posters, ads, business cards) — often premature, as most phones couldn't scan natively
2017 — iOS 11 adds native QR scanning in the Camera app — a turning point
2018 — Android follows with native camera QR support
2020-2021 — COVID-19 pandemic triggers explosive adoption: contactless menus, vaccination certificates, health check-ins, digital payments
2022+ — QR codes become a permanent fixture in daily life across payments, authentication, ticketing, and more

The COVID-era explosion was remarkable. In 2020 alone, QR code interactions increased by 94% globally. Restaurants replaced physical menus with QR-code-linked digital menus virtually overnight. Governments issued vaccination certificates as QR codes. What had been an occasionally-used technology became an essential part of daily life in a matter of months.

QR Code Structure

Every component has a precise purpose.

QR Code Component Map (Version 7 example, 45x45 modules) ┌──────────┐ ┌──────────┐ │ FINDER │ Timing Pattern (row) │ FINDER │ │ PATTERN │ . . . . . . . . . . │ PATTERN │ │ (top-L) │ │ (top-R) │ └──────────┘ └──────────┘ │ Format Info │ │ (15 bits x2) │ T T i ┌───────────────────────────────┐ i m │ │ m i │ DATA + ERROR CORRECTION │ i n │ CODEWORDS │ n g │ │ Alignment g │ (placed in 2-column │ Pattern P │ zigzag from bottom-right) │ (5x5) P a │ │ a t └───────────────────────────────┘ t t t . Version Info (for V7+) . ┌──────────┐ Version Info │ FINDER │ (18 bits x2) │ PATTERN │ │ (bot-L) │ Quiet Zone (4 modules white border) └──────────┘

Component Details

Finder Patterns

Three identical 7x7 module patterns in the top-left, top-right, and bottom-left corners. Each consists of a 3x3 black center, surrounded by white, surrounded by black. The unique 1:1:3:1:1 width ratio is detectable from any angle and allows instant position and orientation detection.

Alignment Patterns

Smaller 5x5 patterns placed at regular intervals in larger QR codes (Version 2+). They help compensate for image distortion (e.g., when a QR code is on a curved surface or photographed at an angle). Version 1 has none; Version 40 has 46.

Timing Patterns

Alternating black and white modules running horizontally and vertically between the finder patterns. They establish the coordinate system, letting the decoder determine the exact number and position of rows and columns, even if the image is slightly warped.

Format Information

15 bits stored adjacent to the finder patterns (duplicated for redundancy). Encodes the error correction level (2 bits) and the mask pattern (3 bits), plus 10 bits of BCH error correction for the format info itself. XORed with a fixed mask to ensure it's never all-zero.

Version Information

Only present in Version 7 and above. 18 bits (6x3 modules) placed near the top-right and bottom-left finder patterns. Encodes the version number (7-40) with Golay error correction. This lets the decoder know the QR code's size without counting modules.

Data & EC Codewords

All remaining modules carry the actual payload: data codewords followed by error correction codewords. They are placed in 2-module-wide columns, zigzagging upward and downward from the bottom-right corner, skipping any reserved areas (finders, timing, alignment, format, version).

Quiet Zone

A 4-module-wide white border must surround the entire QR code. This empty space lets the scanner clearly distinguish the code from its surroundings. Violating the quiet zone (e.g., placing the code too close to other graphics) is one of the most common causes of scanning failures.

Encoding Data

Four modes, one pipeline, maximum density.

The Four Encoding Modes

ModeIndicatorCharacter SetBits/CharEfficiency
Numeric00010-93.33 (10 bits / 3 digits)Highest
Alphanumeric00100-9, A-Z, space, $%*+-./:;5.5 (11 bits / 2 chars)High
Byte0100ISO 8859-1 (or UTF-8)8Medium
Kanji1000Shift JIS double-byte13For Japanese text

Mode switching is supported within a single QR code. If your data contains a phone number followed by a URL, the encoder can switch from Numeric mode to Byte mode mid-stream. Each switch costs 4 bits for the mode indicator plus the character count indicator, so good encoders optimize when to switch to minimize total size.

Capacity by Version

VersionSizeNumeric (L)Alphanumeric (L)Byte (L)
121 × 21412517
537 × 3720212284
1057 × 57652395271
2097 × 972,0611,249858
30137 × 1374,1582,5201,732
40177 × 1777,0894,2962,953

The Encoding Pipeline

Data Analysis
→
Mode Encoding
→
Error Correction
→
Matrix Placement
→
Masking
→
Format Info

1. Data Analysis: Examine the input string and determine the optimal mode(s) and the smallest QR version that fits the data at the desired error correction level.

2. Mode Encoding: Encode the data according to the chosen mode. Add mode indicator (4 bits), character count indicator (variable length), and encoded data bits. Pad to fill the version's capacity: add terminator (0000), pad to byte boundary, then alternate pad bytes 0xEC and 0x11.

3. Error Correction: Split data into blocks (more blocks in higher versions), compute Reed-Solomon error correction codewords for each block, then interleave data and EC codewords.

4. Matrix Placement: Place the interleaved bit stream into the QR matrix in 2-module-wide columns, zigzagging from the bottom-right corner, skipping reserved areas (finder/timing/alignment patterns, format/version info areas).

5. Masking: Apply each of the 8 mask patterns, evaluate the penalty score for each, and select the pattern with the lowest penalty.

6. Format Info: Encode the chosen error correction level and mask pattern into the format information bits and place them in the reserved areas.

Error Correction

The math that lets damaged codes still work.

QR codes use Reed-Solomon error correction, the same class of codes used in CDs, DVDs, deep-space communication, and RAID storage. It can correct errors (wrong modules) and detect erasures (missing modules), making QR codes remarkably resilient to physical damage.

Four Error Correction Levels

LevelRecovery CapacityData OverheadBest For
L (Low)~7% of codewords~20%Clean environments, maximum data capacity
M (Medium)~15% of codewords~38%General use (the default for most generators)
Q (Quartile)~25% of codewords~55%Factory environments, moderate wear
H (High)~30% of codewords~65%Harsh environments, codes with logos
The Tradeoff

Higher error correction means more of the QR code is dedicated to redundancy and less to actual data. At level H, nearly two-thirds of the code is error correction data. For the same amount of data, a level H code must be a larger version (more modules) than a level L code.

The Math: Galois Field GF(256)

Reed-Solomon codes operate over GF(256), a finite field (also called a Galois Field) with exactly 256 elements (matching one byte). In this field:

Addition is XOR (bitwise exclusive-or). This means addition and subtraction are the same operation, which simplifies the hardware enormously.

Multiplication is polynomial multiplication modulo an irreducible polynomial. QR codes use the polynomial x^8 + x^4 + x^3 + x^2 + 1 (0x11D). In practice, multiplication is done via lookup tables of logarithms and anti-logarithms (powers of the generator element α = 2).

The generator polynomial is constructed as the product of factors (x - α^0)(x - α^1)...(x - α^(n-1)) where n is the number of error correction codewords. The data polynomial is divided by this generator, and the remainder becomes the EC codewords.

Decoding involves computing syndromes, finding the error locator polynomial (via the Berlekamp-Massey or Euclidean algorithm), finding error positions (Chien search), and computing error values (Forney algorithm).

Why Logos Work in the Center

When you see a QR code with a company logo placed over the center, it works because the logo is destroying some modules — but the error correction has enough redundancy to recover the lost data. This is why logos in QR codes require level H (30%) error correction, and the logo must not exceed approximately 30% of the code area. The center of the QR code is chosen because it's furthest from the finder patterns and format information, so the remaining structural elements are preserved.

A Warning About Logos

Adding a logo reduces the code's ability to survive additional damage. A QR code at level H with a logo consuming 25% of modules has used most of its error correction budget for the logo alone, leaving very little margin for dirt, scratches, or printing defects. Always test extensively.

Masking

Why raw data placement creates scanability problems, and how masking fixes them.

After data and error correction bits are placed in the QR matrix, the resulting pattern might contain large regions of the same color, or patterns that look like finder patterns, confusing the scanner. Masking is an XOR operation applied to every data module (not function patterns) to break up these problematic patterns.

The 8 Mask Patterns

The QR specification defines exactly 8 mask patterns. Each is a formula that determines, for any module at position (row, col), whether to flip that module's color:

Mask Pattern Formulas (module is flipped if condition = 0) Pattern 0: (row + col) mod 2 == 0 Checkerboard Pattern 1: row mod 2 == 0 Horizontal stripes Pattern 2: col mod 3 == 0 Vertical stripes (every 3rd) Pattern 3: (row + col) mod 3 == 0 Diagonal stripes Pattern 4: (row/2 + col/3) mod 2 == 0 Block pattern Pattern 5: (row*col)%2 + (row*col)%3 == 0 Complex cross Pattern 6: ((row*col)%2 + (row*col)%3)%2 == 0 Rounded blocks Pattern 7: ((row+col)%2 + (row*col)%3)%2 == 0 Diagonal blocks

Evaluation: Choosing the Best Mask

The encoder applies all 8 masks and evaluates each result against four penalty rules. The mask with the lowest total penalty score wins:

RuleWhat It PenalizesPenalty
N1Runs of 5+ same-color modules in a row/column3 + (run length - 5) per run
N22x2 blocks of same-color modules3 per block
N3Patterns resembling finder pattern (1:1:3:1:1)40 per occurrence
N4Imbalance in dark vs. light module ratio10 per 5% deviation from 50%

Rule N3 is particularly important: if the data placement accidentally creates patterns that look like the 1:1:3:1:1 ratio of finder patterns, scanners might detect false finder patterns and fail to decode the QR code. The heavy penalty (40 points) strongly discourages these patterns. The entire masking process is deterministic — any standard-compliant encoder will choose the same mask for the same input data.

How Scanning Works

From camera image to decoded data in milliseconds.

Capture Image
→
Find Finders
→
Determine Geometry
→
Undistort
→
Sample Modules
→
Unmask
→
Error Correct
→
Decode

1. Image Capture: The camera captures a frame. The image may contain the QR code at any position, size, angle, or perspective distortion.

2. Locate Finder Patterns: The decoder scans rows and columns looking for the distinctive 1:1:3:1:1 dark-light-dark-light-dark ratio. When three such patterns are found forming a right triangle, a QR code candidate is identified. The three finder patterns establish position, orientation, and scale.

3. Determine Version & Format: Read the format information bits (adjacent to finders) to learn the error correction level and mask pattern. For larger codes, read version information to determine the exact size. Count modules between finders to confirm.

4. Perspective Correction: Using the three finder pattern centers (and alignment patterns if present), compute an affine or perspective transformation to rectify the image into a perfect square grid. This corrects for camera tilt and lens distortion.

5. Sample Modules: Map each module position to its corresponding pixel location in the rectified image. Determine if each module is black (1) or white (0) using adaptive thresholding (important for varying lighting conditions).

6. Unmask: Apply the mask pattern (identified from format info) by XORing the data modules. This reverses the masking applied during encoding.

7. Error Correction: Read the data and EC codewords in the placement order (2-column zigzag). De-interleave into blocks. Apply Reed-Solomon decoding to each block to detect and correct any errors.

8. Decode Data: Parse the corrected bit stream: read mode indicators, character counts, and data segments. Handle mode switches. Output the final decoded string, URL, or binary data.

Modern smartphone decoders can complete this entire pipeline in 10-50 milliseconds per frame. Advanced implementations use machine learning to improve finder pattern detection under poor lighting, blur, or partial occlusion. Some decoders process multiple frames simultaneously, combining partial reads to reconstruct damaged or partially visible codes.

Data Matrix

The workhorse of industrial micro-marking.

Data Matrix is a 2D barcode symbology that excels in situations where space is extremely limited. Developed by International Data Matrix Inc. (now Cognex), it's widely used for marking tiny electronic components, surgical instruments, pharmaceutical vials, and circuit boards (PCBs) where a QR code simply won't fit.

Key Features

L-Shaped Finder

Instead of QR's three corner squares, Data Matrix uses an L-shaped solid border along the bottom and left edges, plus an alternating (clock) border along the top and right. The L finder determines position and orientation.

ECC 200

The modern standard (ECC 200) uses Reed-Solomon error correction, capable of recovering up to 28% of the data. Older versions (ECC 000-140) used convolutional codes and are now obsolete.

Tiny Size

The smallest Data Matrix is 10x10 modules (compared to QR's minimum 21x21). This can be printed at just 2-3mm square and still be readable with appropriate scanners. This makes it ideal for direct part marking (DPM).

Direct Part Marking

Data Matrix codes can be laser-etched, dot-peened, or chemically etched directly onto metal, glass, and plastic parts. This permanent marking survives extreme conditions: heat treatment, painting, sandblasting, and years of use.

Data Matrix vs. QR Code

FeatureData MatrixQR Code
Minimum size10x10 modules21x21 modules
Maximum size144x144 modules177x177 modules
Max numeric capacity3,1167,089
Finder patternL-shaped borderThree corner squares
Error correctionReed-Solomon (up to 28%)Reed-Solomon (up to 30%)
Primary useIndustrial / DPMConsumer / marketing
Smartphone supportLimitedUniversal

Aztec Codes

Bullseye finder, no quiet zone, built for tickets.

Invented in 1995 by Andrew Longacre at Welch Allyn (now Honeywell), the Aztec code takes a fundamentally different approach to finder patterns. Instead of corner markers, Aztec codes feature a distinctive central bullseye — concentric square rings in the center of the code. This design inspired the name, after the bird's-eye view of an Aztec pyramid.

Key Advantages

No Quiet Zone Required

Aztec codes are the only major 2D symbology that requires no quiet zone. The central bullseye is so distinctive that it can be found even when the code is surrounded by other graphics or text. This saves space in print layouts.

Compact & Full-Range

Compact Aztec: 1-4 layers around a 9x9 core (15x15 to 27x27 modules). Full-range Aztec: 1-32 layers around an 11x11 core (19x19 to 151x151 modules). Up to 3,832 numeric or 3,067 alphanumeric characters.

Where You'll See Them

Airline boarding passes: The IATA BCBP (Bar Coded Boarding Pass) standard uses Aztec codes. Next time you fly, look at your mobile or paper boarding pass — that's an Aztec code. European train tickets: Deutsche Bahn, SNCF, and other European rail operators use Aztec codes on mobile tickets. Government IDs: Some jurisdictions use Aztec codes on driver's licenses and identity documents.

The choice of Aztec for transportation tickets comes down to the no-quiet-zone advantage (space is limited on boarding passes) and the fact that the central bullseye can be detected rapidly even at low resolution or under poor scanning conditions.

PDF417

The stacked barcode that bridges 1D and 2D.

PDF417 (Portable Data File, 4 bars, 1-7 units each) is technically a stacked linear barcode rather than a true 2D matrix code. It arranges data in multiple rows of linear bar patterns, creating a rectangular shape. Invented by Ynjiun Wang at Symbol Technologies in 1991.

How It Works

Each row in a PDF417 code is essentially an independent linear barcode. A row contains: a start pattern, a left row indicator, 1-30 data codewords, a right row indicator, and a stop pattern. The rows stack vertically, with each row independently decodable. Error correction uses Reed-Solomon codes with configurable levels (0-8), providing recovery of up to 510 codewords.

Massive Capacity

PDF417 can hold up to 2,710 numeric or 1,850 alphanumeric characters, or 1,108 bytes of binary data. This is enough for a full text paragraph, a small image (compressed), or biometric data.

Where It's Used

U.S. driver's licenses (AAMVA standard), shipping labels (especially USPS), government documents, and airline bag tags. The REAL ID Act mandates PDF417 on all compliant licenses.

Comparison of 2D Code Symbologies

FeatureQR CodeData MatrixAztecPDF417
TypeMatrixMatrixMatrixStacked linear
Finder3 corner squaresL-shaped borderCentral bullseyeStart/stop per row
ShapeSquareSquare / RectangleSquareRectangle
Max numeric7,0893,1163,8322,710
Quiet zone4 modules1 moduleNone2 modules
Error correctionRS (7-30%)RS (up to 28%)RS (5-95%)RS (configurable)
Best forConsumer, mobileIndustrial, tiny partsTickets, transportIDs, documents
Year1994198719951991

Retail & Inventory

How a barcode gets on a product and what happens when it's scanned.

The GS1 System

GS1 is the non-profit organization that administers the global barcode standards. Every barcode on a retail product starts here. The core identifier is the GTIN (Global Trade Item Number), which can be 8, 12, 13, or 14 digits long:

GTIN-13 Structure (EAN-13) 471 1234 56789 0 471 — GS1 prefix (Taiwan) 1234 — Company prefix (assigned by GS1 Taiwan) 56789 — Item reference (assigned by the company) 0 — Check digit Note: The GS1 prefix indicates where the company is registered, NOT where the product was manufactured.

The Journey of a Barcode

Company joins GS1
→
Receives company prefix
→
Assigns item numbers
→
Prints on packaging
→
Scanned at POS

When a cashier scans a product, the barcode number itself doesn't contain the price. Instead, the POS (Point of Sale) system looks up the GTIN in the store's database to retrieve the product name, price, and other information. This is why the same product might have different prices at different stores — each store maps the same barcode to their own pricing.

Barcode Databases

Several databases map GTINs to product information: GS1 GDSN (the official global data synchronization network), Open Food Facts (open-source food product database), UPC Database, and various commercial APIs (Barcodelookup, UPCitemdb). Inventory management systems use continuous scanning with handheld devices to track stock levels in real time, trigger reordering, and reduce shrinkage. Modern warehouses scan products at every stage: receiving, put-away, picking, packing, and shipping.

Mobile Payments

QR codes as a global payment revolution.

QR-code-based payments have become the dominant payment method in several major economies, processing trillions of dollars annually. The approach varies by region but the core concept is simple: transfer payment information through a scannable code instead of a physical card.

Two Presentation Modes

Merchant-Presented

The merchant displays a static or dynamic QR code. The customer scans it with their payment app, confirms the amount, and pays. Static codes (printed on a card or sticker) are cheap and work for small vendors — the customer enters the amount manually. Dynamic codes (shown on a screen) include the exact amount for the specific transaction.

Customer-Presented

The customer opens their payment app, which displays a QR code (usually refreshed every 30-60 seconds for security). The merchant scans this code with their POS terminal. This is faster and more secure, as the code is dynamic and time-limited, but requires the merchant to have a scanner.

Major QR Payment Systems

SystemRegionAnnual VolumeModel
WeChat PayChina~$10T+ combined with AlipayBoth modes
AlipayChina / Global(part of above)Both modes
UPI (BHIM, GPay, PhonePe)India~$2T+ (2024)Both modes
PixBrazil~$1T+ (2024)Both modes
PromptPayThailandGrowing rapidlyBoth modes
PayNowSingaporeGrowing rapidlyBoth modes

Security Considerations

QR code swapping attacks: A criminal places a sticker with their own QR code over a merchant's legitimate payment QR. Customers unknowingly pay the attacker instead of the merchant. This is a significant real-world problem, especially for static merchant-presented codes. Mitigations include: tamper-evident printing, dynamic codes on screens, merchant verification in the payment app (showing the merchant name before confirming), and regular physical inspection of displayed codes.

Tokenization: Modern QR payment systems don't embed actual account numbers. Instead, they use tokenized references that are only valid for a limited time and specific transaction context. Even if intercepted, the QR code's data cannot be reused.

Authentication & 2FA

The QR code that secures your accounts.

When you enable two-factor authentication with an app like Google Authenticator, Authy, or 1Password, you typically scan a QR code. That QR code contains a TOTP (Time-based One-Time Password) secret encoded in a specific URI format.

The otpauth:// URI Format

otpauth://totp/Example:user@example.com? secret=JBSWY3DPEHPK3PXP &issuer=Example &algorithm=SHA1 &digits=6 &period=30 secret — Base32-encoded shared secret (the core cryptographic key) issuer — Service name displayed in the authenticator app algorithm — Hash algorithm (SHA1, SHA256, SHA512; default SHA1) digits — Number of digits in the code (default 6) period — How often the code changes, in seconds (default 30)

How TOTP Works After Scanning

1. The QR code transfers the shared secret to your authenticator app (one-time transfer).
2. Both the server and your app now share the same secret key.
3. Every 30 seconds, both sides independently compute: HMAC-SHA1(secret, floor(unix_time / 30))
4. The HMAC result is truncated to 6 digits using dynamic truncation.
5. When you enter the 6-digit code at login, the server computes the same value and checks for a match (typically accepting the current period ±1 for clock drift).

Security Implication

The QR code contains the complete shared secret in plaintext. Anyone who photographs this QR code can clone your 2FA. Never share screenshots of 2FA setup QR codes. If you suspect the secret has been compromised, immediately disable and re-enable 2FA to generate a new secret.

Digital Menus & Marketing

The QR code renaissance that COVID built.

The COVID-19 pandemic transformed QR codes from a niche technology into an everyday necessity. Restaurants, forced to eliminate shared physical menus, adopted QR codes almost overnight. A table tent with a QR code linking to a digital menu became ubiquitous worldwide, and the habit has largely persisted.

Static vs. Dynamic QR Codes

Static QR

Encodes the destination URL directly. Cannot be changed after printing. If the URL changes, you need a new QR code. Simpler, no dependencies on third-party services, works offline. The encoded data is the final URL itself.

Dynamic QR

Encodes a short redirect URL (e.g., qr.example.com/abc123). The redirect destination can be changed at any time without reprinting the QR code. Enables scan analytics (count, location, device, time). Requires a working redirect service.

Analytics & Tracking

Dynamic QR codes opened up a marketing analytics channel. When a user scans a dynamic QR code, the redirect service can capture: timestamp, geographic location (from IP), device type (iOS/Android/desktop), browser, and scan count. This data lets marketers measure engagement with physical print campaigns, billboards, product packaging, and event materials in ways that were previously impossible.

The combination of URL shorteners + QR codes has become standard practice. Services like Bitly, QR Code Generator, and Beaconstac provide both URL shortening and QR code generation with integrated analytics dashboards. A typical flow: create a short URL, generate a branded QR code for it, place it on physical materials, and monitor scan performance in real time.

The Post-COVID Reality

While the initial adoption was driven by hygiene concerns, QR codes have remained because they are genuinely more convenient. Restaurants can update menus instantly (no reprinting), add photos, handle multiple languages, and even enable direct ordering from the phone. QR codes at tables have reduced the need for wait staff to deliver menus, take drink orders, and process payments.

QR Code Security

The dark side of point-and-scan convenience.

The same frictionless experience that makes QR codes useful also makes them dangerous. Users have been trained to scan first and ask questions later, which creates a rich attack surface for criminals.

Attack Vectors

Quishing (QR Phishing)

QR codes in phishing emails bypass URL preview protections. Traditional email filters scan clickable links but often cannot decode and inspect QR codes embedded as images. The user scans the QR code with their phone, leaving the protected corporate network entirely, and lands on a credential-harvesting site.

Overlay Attacks

Criminals stick their own QR code stickers over legitimate ones on parking meters, restaurant tables, or payment terminals. The user scans what they believe is a legitimate code. Difficult to detect because QR codes are inherently opaque — you can't see the URL before scanning.

Malicious Payloads

QR codes can encode not just URLs but also Wi-Fi credentials, phone numbers (triggering calls), SMS messages, calendar events, and app store links. An attacker could set up a QR code that connects your phone to a malicious Wi-Fi network for traffic interception.

Social Engineering

Fake "scan to claim your prize" QR codes in public places, fake parking tickets with QR codes directing to payment fraud sites, fake utility bills with altered QR payment codes. The physical nature of QR codes lends them an air of legitimacy.

Defenses

For users: Always check the URL after scanning before tapping through. Use a QR scanner that previews the URL prominently. Be suspicious of QR codes in unexpected places (stickers on top of other stickers, QR codes taped to surfaces). Never scan QR codes in unsolicited emails.

Secure QR Codes: Some implementations embed a digital signature within the QR data. The scanning app verifies the signature against a trusted certificate before taking action. The EU Digital COVID Certificate used this approach: each vaccination QR code contained a cryptographic signature from the issuing health authority, making forgery computationally infeasible.

Physical Limitations

Real-world constraints on printed codes.

Print Size & Resolution

Every barcode has a minimum module size (the smallest bar or dot). For standard retail scanning, the minimum module width is about 0.264mm (10.4 mils) for UPC codes. For QR codes intended for smartphone scanning, each module should be at least 0.33mm, giving a minimum QR code size of about 10mm x 10mm for Version 1 (21 modules). Larger versions need proportionally larger print areas or higher resolution printing.

Key Physical Constraints

ConstraintBarcodeQR CodeNotes
Min print size~20mm wide~10mm squareDepends on version/density
Contrast ratio> 50% difference> 40% differenceDark on light; avoid colored backgrounds
Scan distanceSize × 6-10Size × 10Larger code = scan from further away
Curved surfacesPoor (distorts widths)Better (2D correction)Keep curve radius > 5x code width
MaterialPaper, plastic, labelAny printableShiny/reflective surfaces cause glare

Durability Factors

Scratches & Wear

1D barcodes are extremely vulnerable to horizontal scratches (they destroy bar-width data). QR codes are more resilient due to 2D redundancy and error correction. For high-wear applications, lamination or protective coatings are essential.

Fading & UV

Sunlight, UV exposure, and thermal degradation reduce contrast over time. Thermal-printed labels (common in shipping) can fade in weeks under direct sun. Laser-etched and inkjet-printed codes last longer. For outdoor use, UV-resistant inks and materials are necessary.

Metallic Surfaces

Codes on metal require special techniques: laser etching (permanent but low contrast), dot peening (durable, reads via shadow), or specialized high-contrast labels. Reflective surfaces cause scanner glare; matte finishes or diffuse lighting help.

Fabric & Flexible

Codes on fabric (clothing tags, wristbands) stretch and distort. QR codes handle this better than 1D barcodes due to alignment patterns and error correction. Woven labels generally outperform printed-on-fabric codes for durability.

The Distance Rule of Thumb

The maximum scanning distance is approximately 10 times the code's width (for QR codes with a standard-resolution camera). A 5cm QR code can be scanned from about 50cm away. A billboard QR code at 1 meter wide could theoretically be scanned from 10 meters. Always test at the intended distance with the intended device.