Calculating EAN-8 / EAN-13 check digits with C#

The following two code snippets show how to create an EAN8 / EAN13 check digit. Both routines also test the supplied data for validness. For both code types the passed data must be purely numeric, for EAN 8 the length must be seven or eight digits, for EAN 13, twelve or thirteen digits. This code snippet can be used for barcode creation but also if you want to validate if an EAN has been read or decoded correctly.

Obviously, the following routines could be written much shorter and much more elegantly.

The following C# source code has been put into the Public Domain.

EAN 8 Checksum with C#

static int _checksum_ean8(String data)
{
    // Test string for correct length
    if(data.Length != 7 && data.Length != 8)
        return -1;
	
    // Test string for being numeric
    for(int i=0;i<data.Length;i++)
    {
        if(data[i] < 0x30 || data[i] > 0x39)
            return -1;
    }

    int sum = 0;

    for(int i=6;i>=0;i--)
    {
        int digit = data[i] - 0x30;
        if ((i & 0x01) == 1)
            sum += digit;
        else
            sum += digit * 3;
    }
    int mod = sum % 10;
    return mod == 0 ? 0 : 10 - mod;
}
    	

EAN 13 Checksum with C#

static int _checksum_ean13(String data)
{
    // Test string for correct length
    if(data.Length != 12 && data.Length != 13)
        return -1;

    // Test string for being numeric
    for(int i=0;i<data.Length;i++)
    {
        if(data[i] < 0x30 || data[i] > 0x39)
            return -1;
    }

    int sum = 0;

    for(int i=11;i>=0;i--)
    {
        int digit = data[i] - 0x30;
        if ((i & 0x01) == 1)
            sum += digit;
        else
            sum += digit * 3;
    }
    int mod = sum % 10;
    return mod == 0 ? 0 : 10 - mod;
}			
		
If you are interested in creating barcodes with C#, make sure to see our .NET barcode SDK.