标签:
1 namespace CheckIdenoDemo 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 Console.WriteLine("请输入您的18位身份证号码:"); 8 string readstring = Console.ReadLine(); 9 10 IdentifyCheck idenCheck = new IdentifyCheck(); 11 12 idenCheck.Identity = readstring; 13 if (idenCheck.Identity == null) 14 { 15 Console.WriteLine("错误码:" + idenCheck.ErrCode + ",错误信息:" + idenCheck.ErrMsg); 16 Console.ReadKey(); 17 return; 18 } 19 20 char checkPoint = idenCheck.CheckMethod(); 21 22 Console.WriteLine("检验码为:" + checkPoint); 23 Console.WriteLine("您输入的码为:" + idenCheck.Identity.Substring(17, 1)); 24 25 Console.ReadKey(); 26 } 27 } 28 29 class IdentifyCheck 30 { 31 #region 属性 32 //错误码 33 private int errCode = 0; 34 public int ErrCode 35 { 36 get 37 { 38 return this.errCode; 39 } 40 set 41 { 42 this.errCode = value; 43 } 44 } 45 46 //错误信息 47 private string errMsg = string.Empty; 48 public string ErrMsg 49 { 50 get 51 { 52 return this.errMsg; 53 } 54 set 55 { 56 this.errMsg = value; 57 } 58 } 59 60 //身份证号码 61 private string identity; 62 public string Identity 63 { 64 65 get 66 { 67 return this.identity; 68 } 69 70 set 71 { 72 if (value == string.Empty || value.Trim() == string.Empty || value.Trim() == "") 73 { 74 this.ErrCode = -1; 75 this.ErrMsg = "身份证号码为空"; 76 return ; 77 } 78 if (value.Length != 18) 79 { 80 this.ErrCode = -1; 81 this.ErrMsg = "身份证号码不够18位"; 82 return ; 83 } 84 this.identity = value; 85 } 86 } 87 88 #endregion 89 90 #region 成员变量 91 92 //权值 93 int[] Weight = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; 94 95 //校验码对照 96 char[] validate = { ‘1‘, ‘0‘, ‘X‘, ‘9‘, ‘8‘, ‘7‘, ‘6‘, ‘5‘, ‘4‘, ‘3‘, ‘2‘ }; 97 98 #endregion 99 100 #region 方法 101 102 /// <summary> 103 /// 身份证校验算法 104 /// </summary> 105 /// <returns></returns> 106 public char CheckMethod() 107 { 108 int mode = 0; 109 int sum = 0; 110 //17位基本数字加权求和 111 for (int i = 0; i < this.Identity.Length - 1; i++) 112 { 113 sum += int.Parse(this.Identity.Substring(i, 1)) * Weight[i]; 114 } 115 116 //计算模 117 mode = sum % 11; 118 119 120 return validate[mode]; 121 } 122 123 #endregion 124 } 125 }
身份证算法如下:
1.十七位数字本体码加权求和公式
S = Sum(Ai * Wi), i= 0,1,...,16,先对前17位数字的权求和。
Ai:表示第i位置上的身份证号码数值(0~9)
Wi:7,9,10,5,8,4,2,1,6,3,7,9,20,5,8,4,2,表示第i位置上的加权因子。
2.计算模
Y = mod(S, 1)
3.根据模,查找得到对应的校验码
Y的值 0 1 2 3 4 5 6 7 8 9 10
校验码 1 0 X 9 8 7 6 5 4 3 2
标签:
原文地址:http://www.cnblogs.com/wangyblzu/p/wangyblzu.html