How to generate a CUSIP check digit in C #

CUSIPs are a 9-digit alphanumeric code to uniquely identify financial security.

https://en.wikipedia.org/wiki/CUSIP

They were invented in 1964 and, given the reliability of data transmission in the 60s, the 9th digit is actually a check digit used to confirm the validity of the first 8 characters. Sometimes even today you may find the reason why you want to check CUSIP, or perhaps a company or service, explicitly decides only to transmit the 8-character CUSIP, even if it defeats the target of the check digit.

Check Digit Generation Procedure:

  • Convert non-numeric digits to values ​​according to their ordinal position in the alphabet plus 9 (A = 10, B = 11, ... Z = 35) and convert the characters * = 36, @ = 37, # = 38.

  • Multiply each even digit by 2

  • If the result of the multiplication is a two-digit number, add the numbers together. (12 = 1 + 2 = 3)

  • Get the sum of all the values.

  • Get the floor value of this operation: (10 - (sum modulo 10)) modulo 10.

What is the best / easiest way to get this value in C #?

+4
source share
2 answers

Answering machine, because yesterday I was looking for this for myself and I want to save someone. I really want to hear more answers or feedback.

public string GenerateCheckDigit(string cusip)
{        
    int sum = 0;
    char[] digits = cusip.ToUpper().ToCharArray();
    string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#";

    for (int i = 0; i < digits.Length; i++)
    {
        int val;
        if (!int.TryParse(digits[i].ToString(), out val))
            val = alphabet.IndexOf(digits[i]) + 10;

        if ((i % 2) != 0)
            val *= 2;

        val = (val % 10) + (val / 10);

        sum += val;
    }

    int check = (10 - (sum % 10)) % 10;

    return check.ToString();
}

Edit:

.NET Fiddle : https://dotnetfiddle.net/kspQWl

+9

, :

private static readonly int[,] Check = new int[128, 2];

static CusipCheckSum() {
    var cusipChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#";
    for (var i = 0 ; i != cusipChars.Length ; i++) {
        Check[cusipChars[i], 0] = i%10 + i/10;
        Check[cusipChars[i], 1] = 2*i%10 + 2*i/10;
    }
}

2D- :

var checkDigit = (10-(cusip.Select((ch, pos) => Check[ch, pos%2]).Sum()%10))%10;
+2

Source: https://habr.com/ru/post/1530464/


All Articles