[技术栈]C#利用Luhn算法(模10算法)对IMEI校验
2024-09-01 07:10:39
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
最新文章
- PHP的数组排序函数
- 性能分析工具-PerfView
- Visual Studio蛋疼问题解决
- WEB中的cookie
- c#部分---结构体再利用;
- git对象存储
- Sphinx编译docs文档
- ARM的两种启动方式 (NAND FLASH. NOR FLASH)
- oracle 10 g 需要启动的2个服务
- PS2键盘 + LCD12864 实验
- SQL truncate 、delete与drop区别
- 关于ReentrantLock和Condition的用法
- [转]smail语法 详解
- YII - 打印 SQL
- qt部件的可视性
- 使用JBolt新建Maven版工程步骤
- Fillder Script语法
- HTTP Status 404 - No result defined for action com.ouyang.action.GreetingAction and result success 错误解决办法
- shell脚本实例-批量检查多个网站地址是否正常
- JAVA设计模式详解(二)----------观察者模式
热门文章
- Vue实现静态数据分页
- 【阿里云IoT+YF3300】4.Alink物模型之事件触发
- 证书pfx转jks
- CF 538 D. Flood Fill 递归 区间DP
- Codeforces Round #383 (Div. 2)D. Arpa&#39;s weak amphitheater and Mehrdad&#39;s valuable Hoses(dp背包+并查集)
- hdu 2895 01背包 Robberies
- yzoj P1412 &; 洛谷P1629 邮递员送信 题解
- Linux入门基础之 中
- java中多线程执行时,为何调用的是start()方法而不是run()方法
- Net基础篇_学习笔记_第十一天_面向对象(面向过程与面向对象的区别/类的概念)