[技术栈]C#利用Luhn算法(模10算法)对IMEI校验

您所在的位置:网站首页 app校验imei码 [技术栈]C#利用Luhn算法(模10算法)对IMEI校验

[技术栈]C#利用Luhn算法(模10算法)对IMEI校验

2023-06-27 15:44| 来源: 网络整理| 查看: 265

1、Luhn算法(模10算法)

通过查看ISO/IEC 7812-1:2017文件可以看到对于luhn算法的解释,如下图:

Luhn算法 算法主要分为三步: 第一步:从右边第一位(最低位)开始隔位乘2; 第二步:把第一步所得的每一个数字加入到原来的数中,比如9*2=18,为1+8; 第三步:用以0结尾且大于第二步所获得的数的和的最小整数减去第二步所获得的和即可以获得校验位,如70-67=3,3即为校验位,如果第二步所有数字的和以0结尾,比如30、40、50等,那么校验为0;

2、IMEI校验 IMEI码由GSM(Global System for Mobile Communications,全球移动通信协会)统一分配,授权BABT(British approvals Board of Telecommunications,英国通信认证管理委员会)审受。 在TS.06 IMEI Allocation and Approval Process中规定IMEI校验应该通过Luhn算法计算,如下图所示: IMEI Allocation and Approval 3、C#代码 public class LuhnCalcCheckDigit { /// /// 通过Luhn算法计算校验位,适合IMEI、银行卡等 /// /// 不包含校验位的号码 /// public static int CalcLuhnCheckDigit(string imei) { int checkDigit = 0; int addValue = 0; for (int i = 0; i < imei.Length; i++) { if (i % 2 == 0) { int result = Convert.ToInt32(imei[imei.Length - i - 1].ToString()) * 2; if (result > 9) { addValue += (result - 9); } else { addValue += result; } } else { addValue += Convert.ToInt32(imei[imei.Length - i - 1].ToString()); } } if (addValue % 10 == 0) { checkDigit = 0; } else { checkDigit = 10 - addValue % 10; } return checkDigit; } /// /// 通过Luhn算法核验号码是否合法,适合IMEI、银行卡等 /// /// 包含校验位的号码 /// public static bool VerifyLuhn(string imei) { int checkDigit = 0; int addValue = 0; for (int i = 1; i < imei.Length; i++) { if (i % 2 == 1) { int result = Convert.ToInt32(imei[imei.Length - i - 1].ToString()) * 2; if (result > 9) { addValue += (result - 9); } else { addValue += result; } } else { addValue += Convert.ToInt32(imei[imei.Length - i - 1].ToString()); } } if (addValue % 10 == 0) { checkDigit = 0; } else { checkDigit = 10 - addValue % 10; } return (checkDigit - Convert.ToInt32(imei[imei.Length - 1].ToString())) == 0; } } 4、参考资料链接

TS.06 IMEI Allocation and Approval Process ISO/IEC 7812-1:2017



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3