public class IdCardTest {public static void main(String[] args) {//原15位身份证号String idCard15 = "410522930308811";StringBuffer sb = get18IdCard(idCard15);System.out.println(sb);}private static StringBuffer get18IdCard(String idCard) {//将字符串转化为buffer进行操作StringBuffer sb = new StringBuffer(idCard);//身份证最后一位校验码,X代表10(顺序固定)char[] checkIndex = {'1','0','X','9','8','7','6','5','4','3','2'};//前17位的总和int sum = 0;//在第6位插入年份的前两位19sb.insert(6,"19");for (int i = 0; i < sb.length(); i++) {char c = sb.charAt(i);//前17位数字int ai = Integer.valueOf(String.valueOf(c));//前17位每位对应的系数(7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 )int wi = ((int) Math.pow(2, sb.length() - i)) % 11;//总和(每位数字乘以系数再相加)sum = sum +ai * wi;}//总和除以11求余int indexOf = sum % 11;//根据余数作为下表在校验码数组里取值sb.append(checkIndex[indexOf]);return sb;} }
最后输出结果:410522199303088111