身份证规则如下:
公民身份证号码是特征组合码,由17位数字本体码和一位数字校验码组成。排列顺序从左至右依次为:六位数字地址码,八位数字出生日期码,三位数字顺序码和一位数字校验码地址码表示编码对象常住户口所在县(市、旗、区)的行政区划代码。生日期码表示编码对象出生的年、月、日,其中年份用四位数字表示,年、月、日之间不用分隔符。顺序码表示在同地址码所标识的区域范围内,对同年、月、日出生的人员编定的顺序号。顺序码的奇数分给男性,偶数分给女性。校验码是根据前面17位数字码,按ISO7064:1983.MOD112校验码计算出来的检验码。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int Chk18PaperId (const char *sPaperId)
{
long lSumQT =0;
//加权因子
int R[] ={7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
//校验码
char sChecker[11]={'1','0','X', '9', '8', '7', '6', '5', '4', '3', '2'};
//检验长度
if( 18 != strlen(sPaperId)) return -1;
//校验数字
int i=0;
for (i=0; i<18; i++)
{
//如果身份证中某一位不是数字或者x的话,则返回-1,失败
if ( !isdigit(sPaperId[i]) && !(('X' == sPaperId[i] || 'x' == sPaperId[i]) && 17 == i) )
{
return -1;
}
}
//验证最末的校验码
for (i=0; i<=16; i++)
{
lSumQT += (sPaperId[i]-48) * R[i];
}
if (sChecker[lSumQT%11] != sPaperId[17] )
{
return -1;
}
return 0;
}
int main()
{
char Personal_ID[18];
printf("请输入一个身份证号码:\n");
while(true)
{
gets(Personal_ID);
if(!Chk18PaperId(Personal_ID))
{
printf("合法\n");
break;
}
else
{
printf("不合法\n请重新输入:\n");
continue;
}
}
system("pause");
return 0;
}