手机IMEI生成工具 生成最后一位 并写入Excel C#版

手机IMEI生成工具 生成最后一位 并写入Excel C#版_第1张图片

import random

def calculate_luhn(pure):
    total = 0
    for i in range(14):
        if i % 2 == 0:
            total += int(pure[i])
        else:
            doubled = int(pure[i]) * 2
            total += (doubled // 10) + (doubled % 10)
    check_digit = (10 - (total % 10)) % 10
    return pure + str(check_digit)

def generate_imei():
    first_14_digits = str(random.randint(10000000000000, 99999999999999))
    return calculate_luhn(first_14_digits)

print(generate_imei())

这个程序首先生成一个14位的随机数,然后使用Luhn算法计算第15位的校验位。Luhn算法是一种简单的校验和算法,用于验证各种身份识别号码,如信用卡号码和IMEI号码。

C# 版

   public static bool imeiCheck(MyDel Log, string IMEI)
   {
       if (IMEI.Length != 15) { Log("IMEI length is " + IMEI.Length + ",it should be 15."); return false; }
       if (!Regex.IsMatch(IMEI, @"^[0-9]*$")) { Log(IMEI + " It should be all numbers."); return false; }
       char check = GetIMEICheckDigit(IMEI.Substring(0, 14));
       if (check != IMEI.Last()) { Log(IMEI + " The last IMEI digit is " + IMEI.Last() + ",it should be " + check); return false; }
       return true; //OK
   }

   public static char GetIMEICheckDigit(string imei)  //生成imei校验位
   {
       int i;
       int sum1 = 0, sum2 = 0, total = 0;
       int temp = 0;

       for (i = 0; i < 14; i++)
       {
           if ((i % 2) == 0)
           {
               sum1 = sum1 + imei[i] - '0';
           }
           else
           {
               temp = (imei[i] - '0') * 2;
               if (temp < 10)
               {
                   sum2 = sum2 + temp;
               }
               else
               {
                   sum2 = sum2 + 1 + temp - 10;
               }
           }
       }

       total = sum1 + sum2;

       if ((total % 10) == 0)
       {
           return '0';
       }
       else
       {
           return (char)(((total / 10) * 10) + 10 - total + '0');
       }
   }

你可能感兴趣的:(智能手机,excel,c#,IMEI)