views:

759

answers:

2

I need to create EAN 8 bar code programmatically. I search an algorithm to calculate the checksum digit.

+3  A: 

The algorithm is covered in this wikipedia article on EAN, note that EAN-8 is calculated in the same way as EAN-13.

Here's a worked example from http://www.barcodeisland.com/ean8.phtml :

Assuming we wish to encode the 7-digit message "5512345", we would calculate the checksum in the following manner:

Barcode          5     5     1     2     3     4     5
Odd/Even Pos?    O     E     O     E     O     E     O
Weighting        3     1     3     1     3     1     3
Calculation    5*3   5*1   1*3   2*1   3*3   4*1   5*3
Weighted Sum    15     5     3     2     9     4    15

The total is 15 + 5 + 3 + 2 + 9 + 4 + 15 = 53. 7 must be added to 53 to produce a number evenly divisible by 10, thus the checksum digit is 7 and the completed bar code value is "55123457".

string code="55123457";

int sum1 = code[1] + code[3] + code[5] 
int sum2 = 3 * (code[0] + code[2] + code[4] + code[6]);
int checksum_value = sum1 + sum2;

int checksum_digit = 10 - (checksum_value % 10);
if (checksum_digit == 10) 
    checksum_digit = 0;
Paul Dixon
+3  A: 
int checkSum(const std::vector<int>& code) const
{
    if (code.size() < 8) return false;

    for( SIZE_T i = 0; i< code.size(); i++ )
    {
     if( code[i] < 0 ) return false;
    }

    int sum1 = code[1] + code[3] + code[5] 
    int sum2 = 3 * (code[0] + code[2] + code[4] + code[6]);

    int checksum_value = sum1 + sum2;
    int checksum_digit = 10 - (checksum_value % 10);
    if (checksum_digit == 10) checksum_digit = 0;

    return checksum_digit;
}
SuperPro
this is incorrect - sum1 should be (code[1] + code[3] + code[5]), sum2 should be 3 * (code[0] + code[2] + code[4] + code[6])
Paul Dixon
OK. Only tested with EAN13. Seems that start weights are different in EAN8 and EAN13...
SuperPro
Digits are counted from the right, so because 8 is even and 13 is odd, they have different weights. Thanks for editing, downvote removed!
Paul Dixon