18th July 2012 Generating and Validating Number Using Luhn Algorithm
18th July 2012 Generating and Validating Number Using Luhn Algorithm
{
var curDigit = (digits[i] - 48);
if (alt)
{
curDigit *= 2;
if (curDigit > 9)
curDigit -= 9;
}
sum += curDigit;
alt = !alt;
}
if ((sum % 10) == 0 )
{
return "0";
}
return (10 - (sum % 10)).ToString();
}
Step 3 - Add check digit obtained from step 2, (output of above function is 8)
So append the output into our original number so the final number including checksum digit is 12345678912345678918.
2. Example - Generating 20 digit number using Luhn Formula, to validate number using Luhn formula, it has to divisible by
10 directly giving reminder 0.
Step1 - pass the number to validate using Luhn formula, we will pass the outcome of our above example that is
12345678912345678918
Step 2 - Validate the number
// method will double every alternate digit starting from the send digit from last
// sum of doubled digits and all other digits,
// if produces 0 if we do modulus onto them than our number is valid else not.
public static bool PassesTheLuhnCheck(string Number)
{
var total = 0;
var alt = false;
var digits = Number.ToCharArray();
for (int i = digits.Length - 1; i >= 0; i--)
{
var curDigit = (int)char.GetNumericValue(digits[i]);
if (alt)
{
curDigit *= 2;
if (curDigit > 9)
curDigit -= 9;
}
total += curDigit;
alt = !alt;
}
return total % 10 == 0;
}
Conclusion,
Luhn formula is widely used and accepted by major organizations.
further readings,
- http://en.wikipedia.org/wiki/Luhn_algorithm [http://en.wikipedia.org/wiki/Luhn_algorithm%20]
- http://www.codeproject.com/Articles/2782/Credit-Card-Validator-control-for-ASP-NET
[http://www.codeproject.com/Articles/2782/Credit-Card-Validator-control-for-ASP-NET]
- http://www.c-sharpcorner.com/Forums/Thread/102218/ [http://www.c-sharpcorner.com/Forums/Thread/102218/]
- http://en.wikipedia.org/wiki/Credit_card_number [http://en.wikipedia.org/wiki/Credit_card_number]
Happy coding!!
Comment as:
Publish
Google Account
Preview
View comments