中国居民身份证号码编码规则
中国居民身份证校验码算法
Java代码示例
public class Validator {
private static final int[] WEIGHTS = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
public static boolean validate(String idCardNumber) {
if (idCardNumber.length() != 18) {
return false;
}
int sum = 0;
for (int i = 0; i < 17; i++) {
char c = idCardNumber.charAt(i);
if (!Character.isDigit(c)) {
return false;
}
int digit = c - '0';
sum += digit * WEIGHTS[i];
}
//取余数
int remainder = sum % 11;
//计算校验码
char expectedCheckDigit = getCheckDigit(remainder);
char actualCheckDigit = idCardNumber.charAt(17);
return expectedCheckDigit == actualCheckDigit;
}
private static char getCheckDigit(int remainder) {
switch (remainder) {
case 0:
return '1';
case 1:
return '0';
case 2:
return 'X';
case 3:
return '9';
case 4:
return '8';
case 5:
return '7';
case 6:
return '6';
case 7:
return '5';
case 8:
return '4';
case 9:
return '3';
case 10:
return '2';
default:
throw new IllegalArgumentException("Invalid remainder: " + remainder);
}
}
}