Back to Blog
Guidesbarcodessymbologycheck-digit

Barcode Symbologies and the Math of Check Digits

How barcode symbologies like EAN-13, UPC-A, and Code 128 differ, and how the mod-10 check digit works, with the arithmetic worked by hand on a real EAN-13.

LoopalooPublished June 5, 202611 min read

Behind every set of black and white stripes is an encoding scheme, and the choice of scheme (the "symbology") determines what characters you can encode, how long the data can be, whether there is built-in error detection, and how a scanner finds the start and end of the message in a noisy image. Pick the wrong symbology and your data either will not fit or will not scan.

Most people meet barcodes through retail: the EAN-13 on a cereal box, the UPC-A on a North American product. Those are only two members of a much larger family, and they happen to be the most rigid ones. Code 128 and Code 39 encode arbitrary text. ITF packs pairs of digits densely for shipping cartons. Each one strikes a different balance between density, character set and self-checking.

This post walks through the common symbologies, explains what each one is for, and then works the mod-10 check digit by hand on a real EAN-13. The code examples use JsBarcode, a popular open-source library for drawing barcodes in the browser, but the arithmetic and the layout rules come from the standards themselves and apply to any generator.

The symbologies, grouped by what they encode

Barcode generators usually sort their formats into three families: general-purpose codes, retail product codes, and industrial or special-purpose codes. The Loopaloo Barcode Generator's format menu uses the same split (Standard, Retail/Product and Industrial), and the grouping maps cleanly onto how the symbologies differ.

SymbologyCharacter setLengthCheck digitTypical use
Code 128All 128 ASCIIVariableYes (mod-103, internal)Shipping labels, logistics
Code 39A-Z, 0-9, a few symbolsVariableOptionalInventory, ID badges
Code 93Same set as Code 39, denserVariableYes (two internal)Compact labeling
EAN-13Digits onlyFixed (13)Yes (mod-10)Retail, international
EAN-8Digits onlyFixed (8)Yes (mod-10)Small retail packaging
UPC-ADigits onlyFixed (12)Yes (mod-10)Retail, North America
UPC-EDigits onlyFixed (compressed)YesSmall North American packages
ITF / ITF-14Digits only, even countVariable / fixed 14Optional / yesCartons, shipping
MSIDigits onlyVariableOptional (mod-10 or mod-11)Warehouse shelving
CodabarDigits and a few symbolsVariableNone standardLibraries, blood banks
PharmacodeEncodes an integer 3-131070VariableNonePharmaceutical packaging

Two distinctions in that table drive almost every practical decision: character set and fixed versus variable length.

Variable length: Code 128 and Code 39

Code 128 is the workhorse for anything that is not a retail product. It covers the full ASCII range through three internal code sets. Set A holds capitals, digits, punctuation and control characters; set B holds all printable ASCII, lower case included; set C encodes digits two at a time, so a numeric string packs into half the symbols. An encoder can switch sets partway through a barcode to keep it short, and most libraries do that automatically while still letting you force a single set.

Set C has one hard constraint: the number of digits must be even, because a final unpaired digit has nothing to pair with. Automatic Code 128 handles an odd count by encoding one of the digits in another set, but if you force set C, a careful generator rejects the input. The Loopaloo generator offers Code 128A, 128B and 128C alongside the automatic version, and tells you the length is odd rather than drawing something wrong.

Code 39 is older and simpler. It encodes 43 characters: capitals, digits, space and a handful of symbols (-, ., $, /, +, %). Each character is a fixed pattern of nine bars and spaces, three of them wide ("3 of 9", hence the name). It is bulky compared with Code 128 but common in legacy industrial and government systems because it is simple to print and decode. Its check character (mod 43) is optional and often omitted. Code 39 also has no lower case, so a generator has to either reject lower-case input or convert it to capitals, and a scanner will read capitals back either way.

Both share a key property: the data length is not baked into the symbology. You can encode A, or you can encode a 40-character serial number. Dedicated start and stop patterns tell the scanner where the message begins and ends.

Fixed length: the retail family

EAN-13, EAN-8, UPC-A and UPC-E are rigid. EAN-13 is always 13 digits. UPC-A is always 12. EAN-8 is 8. There is no "encode whatever you want" mode, because the structure is allocated: a number-system or country prefix, a manufacturer code, a product code, and a final check digit. The whole point of the global GS1 system is that the same 13 digits mean the same product everywhere, so the format cannot flex.

That rigidity makes validation straightforward: count the digits and check the last one. A sensible EAN-13 validator accepts two lengths. Given 12 digits, it computes the check digit and appends it; given 13, it verifies the final digit and rejects the code if it is wrong. A minimal version looks like this (checkDigitFor is defined in the next section):

function parseEan13(input) {
  const digits = input.trim();
  if (!/^\d{12,13}$/.test(digits)) {
    return { ok: false, error: 'EAN-13 needs 12 digits, or 13 with the check digit' };
  }
  const expected = checkDigitFor(digits.slice(0, 12));
  if (digits.length === 12) {
    return { ok: true, value: digits + expected };
  }
  if (Number(digits[12]) !== expected) {
    return { ok: false, error: 'The check digit should be ' + expected };
  }
  return { ok: true, value: digits };
}

The same compute-or-verify pattern covers the rest of the retail family: UPC-A takes 11 or 12 digits, EAN-8 takes 7 or 8, and ITF-14 takes 13 or 14. The Loopaloo Barcode Generator behaves this way. Type 12 digits for an EAN-13 and it tells you which check digit it computed and appended; type 13 with a wrong final digit and it tells you what the check digit should be, instead of drawing a barcode that a scanner would reject.

The mod-10 check digit, worked by hand

EAN-13, EAN-8, UPC-A and ITF-14 all use the same check digit algorithm, defined by GS1. In words: number the data digits from the right, starting at 1. Multiply every digit in an odd position by 3, leave every digit in an even position as it is, and add everything up. The check digit is whatever you need to add to reach the next multiple of 10.

In code, it fits in a few lines:

// GS1 mod-10 check digit for a string of data digits
function checkDigitFor(data) {
  let sum = 0;
  for (let pos = 1; pos <= data.length; pos++) {
    const digit = Number(data[data.length - pos]); // pos 1 is the rightmost digit
    sum += pos % 2 === 1 ? digit * 3 : digit;
  }
  return (10 - (sum % 10)) % 10;
}

Here it is by hand on a widely used sample EAN-13, 5901234123457. The first 12 digits are the data, and the final 7 is the check digit to confirm.

Data: 5 9 0 1 2 3 4 1 2 3 4 5

Number these from the right. Position 1 is the rightmost data digit (5), position 12 is the leftmost (5). Odd positions (1, 3, 5, 7, 9, 11) get the x3 weight; even positions get x1.

DigitValuePosition from rightWeightContribution
5 (leftmost)512x15
9911x327
0010x10
119x33
228x12
337x39
446x14
115x33
224x12
333x39
442x14
5 (rightmost data)51x315

Sum: 5 + 27 + 0 + 3 + 2 + 9 + 4 + 3 + 2 + 9 + 4 + 15 = 83.

Now 83 mod 10 = 3, and the check digit is (10 - 3) % 10 = 7. That matches the 7 printed at the end of 5901234123457, so the barcode is valid.

The weights are chosen with care. Because neither 1 nor 3 shares a factor with 10, changing any single digit always changes the remainder, so a one-digit misread is always caught and the scan is rejected rather than silently accepted. Swapping two neighboring digits is caught too, unless the two digits differ by exactly 5.

Why the outer % 10

The final (10 - (sum % 10)) % 10 has a small but important wrapper. If sum % 10 is already 0, then 10 - 0 = 10, which is not a single digit. The outer % 10 folds that back to 0. Without it, a data string whose weighted sum is an exact multiple of 10 would produce an invalid two-character "digit". It is the kind of edge case that slips past casual testing and breaks naive implementations.

UPC-A is the same math, shorter

UPC-A uses 11 data digits instead of 12, with exactly the same weighting, so the same function serves UPC-A, EAN-8 and ITF-14 without modification. Only the number of digits going in changes. (UPC-A is, in fact, an EAN-13 with a leading zero, which is why a 12-digit UPC and a 13-digit EAN that starts with 0 identify the same product.)

UPC-E adds one twist. It is a zero-suppressed form of a UPC-A: six digits on the label stand for a 12-digit UPC-A with its zeros squeezed out, and the UPC-E check digit is the check digit of that expanded UPC-A, not of the six digits you can see. You cannot compute a correct UPC-E check digit without expanding the code first.

MSI is a different mod-10

MSI barcodes also describe their scheme as "mod 10", but the calculation is different: it doubles alternate digits and sums the digits of the result, much like the Luhn algorithm used for credit card numbers. MSI can also chain two check digits (mod 10 twice, or mod 11 followed by mod 10). "Mod 10" names a family of techniques rather than one specific calculation, so never assume an MSI check digit and an EAN check digit are computed the same way.

Quiet zones: the part that is not bars

A barcode is useless without its quiet zone, the blank margin on either side of the bars. The scanner needs that clear runway to detect where the symbol starts and to set its black and white threshold. The GS1 specification asks EAN-13 for a left quiet zone of 11 modules and a right one of 7; UPC-A wants 9 on each side; Code 128, Code 39 and ITF ask for at least 10 on each side. A "module" is the width of the narrowest bar, so the quiet zone scales with the printed size.

Because the requirement is counted in modules, a margin set in fixed pixels is a common mistake. With a 2-pixel module, a 10-pixel margin is only 5 modules: short of the 7 that EAN-13 needs on the right, and less than half of the 11 it needs on the left. Make the bars wider and a fixed margin falls further behind. The fix is to derive the margins from the module width. JsBarcode accepts separate left and right margins, so it looks like this:

// Minimum quiet zones in modules: [left, right]
const QUIET_ZONES = {
  EAN13: [11, 7],
  UPC: [9, 9],
  CODE128: [10, 10],
};

const moduleWidth = 2; // pixels per narrowest bar
const [left, right] = QUIET_ZONES.EAN13;

JsBarcode('#barcode', '590123412345', {
  format: 'EAN13',
  width: moduleWidth,
  height: 100,
  marginLeft: left * moduleWidth,
  marginRight: right * moduleWidth,
});

The practical failure here is real: people crop a barcode tight to the bars to save space, the quiet zone disappears, and the symbol will not scan even though every bar is perfect. If you place a generated barcode into a larger design, keep that light margin. For raster images, also keep the narrowest bar a whole number of pixels, ideally two or more, so printing or resizing does not smear it.

In the Loopaloo Barcode Generator, the Bar Width setting is the module width and the quiet zones grow with it. Above the preview, it reports the narrowest bar in pixels and the quiet zone on each side in modules, measured from the finished image, next to the minimum the standard asks for.

What a barcode library actually generates

It is easy to over-claim what a barcode tool does, so it helps to be precise.

A library like JsBarcode renders the symbology. It takes your data, applies the encoding rules for the chosen format, computes the check digit where the standard defines one, and draws the bars into a canvas, an SVG element or an image. It is a generator, not a database. It does not assign you a GS1 company prefix, does not check whether a product code is registered, and cannot tell whether your EAN-13 belongs to a real product. A barcode that scans perfectly can still be commercially meaningless if the number was not allocated to you by GS1.

What a generator can do is make sure the barcode is well formed, and that starts with validating input before rendering. Checking the character set and the check digit up front lets you show a clear message, such as "the check digit should be 7, not 3", as the user types, rather than a cryptic rendering error. Formats with their own quirks deserve specific messages: Code 39 input in lower case, an odd-length Code 128C string, a UPC-E whose number-system digit is not 0 or 1.

The strongest check is to read the result back. Decoding the bars from the rendered image and comparing them with the pattern the standard specifies catches anything that went wrong between the data and the pixels. The Loopaloo generator does this for EAN-13, EAN-8 and UPC-A and shows the result above the preview.

Choosing a symbology, quickly

If you are deciding which format to generate:

  • Encoding letters or mixed text, variable length: Code 128 (or Code 39 for legacy systems that require it).
  • A retail product for sale, outside North America: EAN-13 (you need a real GS1 prefix for commercial use).
  • A retail product in North America: UPC-A.
  • Tiny package with no room for 13 digits: EAN-8 or UPC-E.
  • A shipping carton holding many units: ITF-14.
  • Internal warehouse or library tracking where any number works: MSI or Codabar.

Keep in mind that a symbology's internal check character protects the scan, not the data. Code 128's mod-103 check catches a misread bar, but it will faithfully encode a typo. Retail codes carry their check digit inside the number itself, so a mistyped EAN usually fails validation before it is ever printed. With variable-length formats, validating the data is up to you.

Try it

You can generate any of these formats with the Loopaloo Barcode Generator. Type 12 digits and it computes and appends the EAN-13 check digit, or type all 13 and check your own arithmetic against the worked example above. To go the other way, the Loopaloo Barcode Reader & Scanner reads a barcode from an image or your camera and verifies its GS1 check digit. Both run in your browser, so your data never leaves your device.

Related Tools

Related Articles