Decoding the Universal Product Code #

A Universal Product Code (UPC) encodes 12 decimal digits into a barcode of 95 binary digits, where a black bar represents 1 and a white space represents 0.

To scan a UPC, choose either side to start. For the first occurrence of black bar, treat its width as the standard width of a 1-bit digit; same for the white space that follows. Now, read towards the other side; 95 bits will be read in total. Note that consecutive black bars or white spaces may be 1, 2, 3 or 4 bits wide.

There are guard patterns of 101 at both ends, and 01010 in the middle. With the guard patterns as borders, divide the remaining 84 bits into two sections, each containing 42 bits.

For each section, split the bits into 6 arrays of 7 bits. If the number of 1's in an array is odd, mark the section containing that array as section A; otherwise mark it as section B.

Replace all 1's with A and 0's with B in section A, and all 1's with B and 0's with A in section B. Then, in a direction from section A towards section B, decode the arrays one by one with the following table:

ArrayNumber
BBBAABA0
BBAABBA1
BBABBAA2
BAAAABA3
BABBBAA4
BAABBBA5
BABAAAA6
BAAABAA7
BAABAAA8
BBBABAA9

This page is released into the public domain under CC0 1.0.