用C#实现由15位身份证号升级到18位的算法 using System; using System.Collections;
public class MyClass { public static void Main(string[] args) { string oldId; if(args.Length > 0) oldId = args[0]; else oldId = "429005811009091"; Console.WriteLine(per15To18(oldId)); }
public static string per15To18(string IdOld) { if (string.IsNullOrEmpty(IdOld) || !System.Text.RegularExpressions.Regex.IsMatch(IdOld, @"^\d{15}$")) throw new Exception("错误!");
//加权因子常数 int[] iW = new int[] { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; //校验码常数 string LastCode = "10X98765432"; //新身份证号 string IdNew; //计算加权值用 int iS = 0;
IdNew = IdOld.Substring(0, 6); // 取得前6位地区码 IdNew += "19"; // 插入年份的前2位数字19 IdNew += IdOld.Substring(6); // 取得后面9位
//进行加权求和 for (int i = 0; i < iW.Length; i++) { iS += int.Parse(IdNew.Substring(i, 1)) * iW[i]; }
//取模运算,得到模值 int iY = iS % 11; //从LastCode中取得以模为索引号的值,加到身份证的最后一位,即为新身份证号。 IdNew += LastCode.Substring(iY, 1);
return IdNew; } }
|