1、Luhn算法(模10算法)

通过查看ISO/IEC 7812-1:2017文件可以看到对于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算法计算,如下图所示:



3、C#代码

public class LuhnCalcCheckDigit
{ /// <summary>
/// 通过Luhn算法计算校验位,适合IMEI、银行卡等
/// </summary>
/// <param name="imei">不包含校验位的号码</param>
/// <returns></returns>
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;
} /// <summary>
/// 通过Luhn算法核验号码是否合法,适合IMEI、银行卡等
/// </summary>
/// <param name="imei">包含校验位的号码</param>
/// <returns></returns>
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

最新文章

  1. PHP的数组排序函数
  2. 性能分析工具-PerfView
  3. Visual Studio蛋疼问题解决
  4. WEB中的cookie
  5. c#部分---结构体再利用;
  6. git对象存储
  7. Sphinx编译docs文档
  8. ARM的两种启动方式 (NAND FLASH. NOR FLASH)
  9. oracle 10 g 需要启动的2个服务
  10. PS2键盘 + LCD12864 实验
  11. SQL truncate 、delete与drop区别
  12. 关于ReentrantLock和Condition的用法
  13. [转]smail语法 详解
  14. YII - 打印 SQL
  15. qt部件的可视性
  16. 使用JBolt新建Maven版工程步骤
  17. Fillder Script语法
  18. HTTP Status 404 - No result defined for action com.ouyang.action.GreetingAction and result success 错误解决办法
  19. shell脚本实例-批量检查多个网站地址是否正常
  20. JAVA设计模式详解(二)----------观察者模式

热门文章

  1. Vue实现静态数据分页
  2. 【阿里云IoT+YF3300】4.Alink物模型之事件触发
  3. 证书pfx转jks
  4. CF 538 D. Flood Fill 递归 区间DP
  5. Codeforces Round #383 (Div. 2)D. Arpa&#39;s weak amphitheater and Mehrdad&#39;s valuable Hoses(dp背包+并查集)
  6. hdu 2895 01背包 Robberies
  7. yzoj P1412 &amp; 洛谷P1629 邮递员送信 题解
  8. Linux入门基础之 中
  9. java中多线程执行时,为何调用的是start()方法而不是run()方法
  10. Net基础篇_学习笔记_第十一天_面向对象(面向过程与面向对象的区别/类的概念)