Check digit or some times known as Check Sum is a character used to verify the correctness of the information, most commonly used places are barcode,credit card numbers, bank account numbers.
General usage is when all the information is numbers but sometimes we have alpha numeric characters in the information and we need to generate the check digit.
First we will go through calculation of check digit with all numbers based on Luhn Algorithm. Consider “14358”.
- In step 1 we multiply every alternate number with “2” going from right to left.
1 4 3 5 8
2 1 2 1 2
2 4 6 5 16 - After that add up all numbers if number is greater than 9 add the digits and take the value. In the above case for “16” we get 1+6=7. So the sum would be 2+4+6+5+7=24.
- Now divide this by 10. 24/10 we get quoitent of 2 and remainder 4. We need the remainder. Check digit would be 10-4=6.
C# program to calculate check digit with numbers.
private static int CheckDigit(string number)
{
List<int> ans = new List<int>();
foreach (var x in number.Reverse().ToList())
{
if (int.TryParse(x.ToString(), out var num))
{
ans.Add(num);
}
}
var sum = 0;
for (int i = 0; i < ans.Count; i++)
{
if (i % 2 == 0)
{
ans[i] = ans[i] * 2;
if (ans[i] > 9)
{
ans[i] = ans[i] % 10 + 1;
}
}
sum += ans[i];
}
sum = 10 - (sum % 10);
if (sum == 10) sum = 0;
return sum;
}
Now when when we have alphanumeric characters in the information all the steps would be same but we have to consider a mapping to the values.We can make use of the alpha numeric character ascii value or we can assign different values like A=10,B=11,C=12 and so on.
C# program for check digit with alphanumeric characters.
private static int CheckDigit(string number)
{
List<int> ans = new List<int>();
foreach (var x in number.Reverse().ToList())
{
if (int.TryParse(x.ToString(), out var num))
{
ans.Add(num);
}
else
{
int temp = (int) x - 48;
ans.Add(temp);
}
}
var sum = 0;
for (int i = 0; i < ans.Count; i++)
{
if (i % 2 == 0)
{
ans[i] = ans[i] * 2;
if (ans[i] > 9)
{
ans[i] = ans[i] % 10 + ans[i]/10;
}
}
sum += ans[i];
}
sum = 10 - (sum % 10);
if (sum == 10) sum = 0;
return sum;
}
Here i am making use of values for alpha numeric value is “ASCII value -48” and generating the check digit.