⌘BABAKOV.NET Let's code!
100% [light] [ru]

Example of EAN13 calculation in C#

The essence of generating the EAN-13 barcode is to find the control digit (the last 13th digit). 
The algorithm for finding this value is as follows:
1) Leave 12 digits (the last 13 - the control digit we are looking for). 
2) Sum the digits at even positions.
3) Multiply the result of point 2 by 3 .
4) Sum the digits at odd positions.
5) Sum the results of points 3 and 4.
6) In the resulting number, subtract the rightmost digit (remainder of division by 10) from 10, if the remainder is 0, then the value is 0.

The resulting result is the value of the control digit.

Now an example of a class implementing this algorithm in C#:

    class MakeBARCODE
    {
        public static string MakeEAN13(long prefix, long code)
        {
            //В случае если префикс или код слишком большие то будет выдана ошибка:
            string result = "ERROR_TOOLONG";
            if ((prefix < 100) && (code < 10000000000))
            {
                //Получаем строку символов (цифр).
                long all_code = prefix * 100000000000 + code;
                string nabor = all_code.ToString();
                //Сумма по чётным позициям.
                int count_chet = int.Parse(nabor[1].ToString()) + int.Parse(nabor[3].ToString()) + int.Parse(nabor[5].ToString()) + int.Parse(nabor[7].ToString()) + int.Parse(nabor[9].ToString()) + int.Parse(nabor[11].ToString());
                //Сумма по нечётным позициям.
                int count_nechet = int.Parse(nabor[0].ToString()) + int.Parse(nabor[2].ToString()) + int.Parse(nabor[4].ToString()) + int.Parse(nabor[6].ToString()) + int.Parse(nabor[8].ToString()) + int.Parse(nabor[10].ToString());
                //Контрольная сумма и контрольный разряд.
                int control_summ = count_chet * 3 + count_nechet;
                int ostatok = control_summ % 10;
                if (!(ostatok == 0))
                {
                    ostatok = 10 - ostatok;
                }
                result = nabor + ostatok.ToString();
            }
            return result;
        }
    }

The MakeEAN13 function receives two parameters: a two-digit prefix of the barcode and a number (barcode number) from these components, the barcode with the control digit is assembled and returned as a string variable.

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.