身份證號碼校驗算法

此算法用於身份證號碼校驗,根據百度百科可供的計算公式編寫 ,本文提供C#和js兩種版本

C#版:

    class IDCard
    {
        public static bool VerifyIDCard(string idCardNum)
        {
            if (idCardNum.Length != 18)
                return false;

            int[] coefficient = new int[] { 07, 09, 10, 05, 08, 04, 02, 01, 06, 03, 07, 09, 10, 05, 08, 04, 02, 01 };
            int[] idNum = new int[18];
            int total = 0;//權重和
            for (int i = 0; i < 18; i++)
            {
                var temp = idCardNum[i] - 48;
                if (temp > 9)
                {
                    if (i==17&&(temp == 40 || temp == 72))//最後一位是X或x特殊情況
                    {
                        temp = 10;
                    }
                    else
                    {
                        return false;
                    }
                }
                total += (coefficient[i] * temp);
            }
            int result = total % 11;
            return result==1;
        }
    }

js版:

function verifyIDCard(idCardNum) {
	if(idCardNum.length != 18)
		return false;
	var coefficient = [07, 09, 10, 05, 08, 04, 02, 01, 06, 03, 07, 09, 10, 05, 08, 04, 02, 01];
	var idNum = [];
	var total = 0; //權重和
	for(var i = 0; i < 18; i++) {
		var temp =  idCardNum[i].charCodeAt() - 48;
		if(temp > 9) {
			if(i == 17 && (temp == 40 || temp == 72)) //最後一位是X或x特殊情況
			{
				temp = 10;
			} else {
				return false;
			}
		}
		total += (coefficient[i] * temp);
	}
	var result = total % 11;
	return result == 1;
}

喜歡的朋友可以使用,轉載請標明出處,謝謝!!!

如果對您有用也可以發個小紅包

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章