The EAN-13 barcode format is the standard barcode used on everyday products across the world, except in the US, where the UPC-A barcode is more popular.
The EAN-13 barcode is a 13 digit barcode, where the first two or three digies are the country code where the manufacturer of the product is registered. The next nine or ten digits are data digits, which adds up to 12 digits. The last digit is the checksum digit.
To calculate the checksum (also known as the parity), we first need add up the 12 digits of the barcode with the weighting applied. For the EAN-13 barcode, the weighting of each digit which is in an odd-numbered position is 1 and for even-numbered positions, the weighting is 3. To find the sum, we need to multiply each digit by its weighting before adding it together.
Once we have the weighted sum, we apply a modulo 10 to the weighted sum, which gets the remainder after applying a modulo of 10 to the weighted sum.
The parity is then 10 - (modulo 10 of the weighted sum).
Now that we have a 13 digit number, we can encode the data we need to print out a barcode. Each digit is represented by a series of bars and spaces. I will represent a bar as 1 and a space as 0 for the rest of the tutorial.
EAN-13 splits up the 12 digits we need to print into two blocks of 6 with a guard bar at the beginning and end of the barcode and one in the middle of the barcode too. The end guard bars are encoded as 101, while the middle guard bar is 01010.
The parity of the barcode is not printed directly, but is rather used to determine which set of encodings we are going to use for each character, which complicates the encoding of the barcode slightly.
For first 6 digits (the left hand side of the barcode) there is an odd and even encoding. The parity defines which encoding to use. The parity check has a 6 digit binary string, where each digit determines whether to use the odd or even encoding set at the position in the parity string. So for example, for a parity of 3, the binary string is 110001, which means that at position 2, we need to use the odd set, and at position 3 we need to use the even set, and so on.
The parity encodings are as follows:
0
111111
1
110100
2
110010
3
110001
4
101100
5
100110
6
100011
7
101010
8
101001
9
100101
For the left hand side encodings then, the encodings are as follows:
Digit
Odd
Even
0
0001101
0100111
1
0011001
0110011
2
0010011
0011011
3
0111101
0100001
4
0100011
0011101
5
0110001
0111001
6
0101111
0000101
7
0111011
0010001
8
0110111
0001001
9
0001011
0010111
The right hand side encodings (the last 6 digits) do not need this and are just encode straight. The encodings are as follows: