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

quantriketoan

Cối xay gió
Staff member
#1
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 < 0x30 || data > 0x39)
return -1;
}

int sum = 0;

for(int i=6;i>=0;i--)
{
int digit = data - 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 < 0x30 || data > 0x39)
return -1;
}

int sum = 0;

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