2014年3月12日水曜日

C#で加重モジュラス11の計算

/// 
/// 加重モジュラス11 計算
/// NW-7
/// 
/// /// 
public static string GetWeightedModulus11(string Value)
{
    bool result = Regex.IsMatch(Value, @"^[0-9]+$");
    if (!result || Value.Length > 12)
    {
        return null;
    }

    int[] weight1 = { 2, 6, 3, 5, 4, 8, 7, 10, 9, 5, 3, 6, };
    int[] weight2 = { 9, 5, 8, 6, 7, 3, 4, 10, 2, 6, 8, 5, };

    try
    {
        int checkDigit = 0;
        for (int i = 0; i < 2; i++)
        {
            checkDigit = 0;
            for (int j = 0; j < Value.Length; j++)
            {
                checkDigit += int.Parse(Value.Substring(Value.Length - 1 - j, 1)) * (i == 0 ? weight1[j] : weight2[j]);
            }
            checkDigit = checkDigit % 11;

            if (checkDigit == 0) return "0";
            if (checkDigit != 1) break;
        }

        return (11 - checkDigit).ToString();
    }
    catch
    { }
    return null;
}

0 件のコメント:

コメントを投稿