C # Implementation of Luhn Algorithm

Source: Internet
Author: User
When using ICCID, some operators use 18 bits, some operators use 19 BITs (ICCID-C contains a checkpoint ). Then the ICCID-C checkpoint algorithm is adopted Luhn algorithm. This algorithm is only used for input error verification of logarithm strings, not for security checks.
Because 18-bit ICCID is used in our system, in order to be compatible with other carriers in the Portability system, we perform the last-bit processing for the 19-bit ICC passed in from outside, for the 19-bit ICCID-C required by the external system, we calculate the parity bit based on the Luhn algorithm, add it to the 18-bit ICCID, and return it to the customer system.
The Luhn algorithm is designed to check input errors. Therefore, if a digit in a numeric string is incorrectly entered, its check bit is different, then the verification function can be implemented.
Basic description of the Luhn algorithm: from the low position (Right to left), the number of the index is an even number multiplied by a value, and the number of the index is an odd number is retained. After such processing, take the numbers corresponding to all bits and # sum. If # sum ends with 0, the check bit is 0. Otherwise, the last digit of # sum is subtracted from the modulo value.
Generally, the Luhn algorithm performs product processing on each line, and there is a special place in the selection of the multiplier, that is, the numbers of the 10 digits 0-9 multiplied by the multiplier result and there cannot be duplicates. For example, if the multiplier is 3, then 2*3 = 6 (the number is 6), 8*3 = 24 (the number is also 6), then if you mistakenly set 2 to 8, we can't check it, But we generally use multiplier, that is, if the multiplier is 2, 2, there will be no such problem.
In addition, there are also a variety of options for modulus. Generally, modulo 10 is relatively simple. For values other than modulo 10, there will also be problems caused by the selection of multiplier, and the use of model 10 involves both. One is the number and the other is the last digit minus the number and, the number and the number may be different, and the finally calculated check bit may be different, but I did not do any in-depth research. There is an optimization selection problem here. Generally, the algorithm of Modulo 10 every second and 2 times is selected, which should be a better choice obtained by practice.

The following is the c # Implementation of Luhn's algorithm. The algorithm is very simple. The example description of this algorithm can be found on the Internet. The c # implementation also finds one, but it feels a bit complicated, not well written. During implementation, I also fixed the modulo 10 to 2 times plus, and did not reserve the specified space on the modulo and the number of multiples.
The following is my implementation.

Code
Public class Luhn
{
/** // <Summary>
/// Luhn computing model 10 "second-plus" verification number
/// </Summary>
/// <Param name = "numberString"> numberString </param>
/// <Returns> </returns>
Public int GetCheckDigit (string numberString)
{
Bool valid = isValidNumberString (numberString );
If (valid = false) throw new ArgumentException ("Invalid parameter.", "numberString ");

Int sum = getMod10Compartment2Sum (numberString );
Return sum % 10 = 0? 0: 10-sum % 10;
}
/** // <Summary>
/// Use the Luhn algorithm to calculate the modulo 10 "interval 2 times plus" to verify the correctness of a data string
/// </Summary>
/// <Param name = "numberStringWithCheckDigit"> numberStringWithCheckDigit </param>
/// <Returns> </returns>
Public bool IsValid (string numberStringWithCheckDigit)
{
Bool valid = isValidNumberString (numberStringWithCheckDigit );
If (valid = false) throw new ArgumentException ("Invalid parameter.", "numberStringWithCheckDigit ");

Int checkDigit =
GetCheckDigit (numberStringWithCheckDigit. Substring (0, numberStringWithCheckDigit. Length-1 ));
Int lastDigit =
Convert. ToInt16 (numberStringWithCheckDigit [numberStringWithCheckDigit. Length-1]. ToString ());
Return lastDigit = checkDigit;
}
/** // <Summary>
/// Calculate the numeric value and
/// </Summary>
/// <Param name = "number"> </param>
/// <Returns> </returns>
Private static int getDigitsSum (int number)
{
Int sum = 0;
For (int I = 0; I <number. ToString (). Length; I ++)
{
Sum + = Convert. ToInt16 (number. ToString () [I]. ToString ());
}

Return sum;
}
/** // <Summary>
/// Calculate the sum of the 10 "2-plus" modulo
/// </Summary>
/// <Param name = "numberString"> numberString </param>
/// <Returns> </returns>
Private static int getMod10Compartment2Sum (string numberString)
{
Int sum = 0;
For (int I = 0; I <numberString. Length; I ++)
{
Int index = numberString. Length-I-1;
If (I % 2 = 1) sum + = Convert. ToInt16 (numberString [index]. ToString ());
Else sum + = getDigitsSum (Convert. ToInt16 (numberString [index]. ToString () * 2 );
}

Return sum;
}
/** // <Summary>
/// Check whether the input numeric string is valid
/// </Summary>
/// <Param name = "numberString"> numberString </param>
/// <Returns> </returns>
Private static bool isValidNumberString (string numberString)
{
If (string. IsNullOrEmpty (numberString ))
{
Return false;
}

String regextext = @ "^ [0-9] + $ ";
Regex regex = new Regex (regextext, RegexOptions. None );
Return regex. IsMatch (numberString. Trim ());
}
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.