校验位算法 Luhn mod N 与简单和
你知道为什么 Luhn mod N 算法 为了创建校验位而执行求和吗将每个偶数放置的字符的值加倍,而不是对所有字符进行简单求和?
用伪代码的话来说:
给出:
var s = "some string i want to create check digit";
你知道为什么 Luhn mod N 基本上是这样做的吗:
for(i from s.length-1 to 0)
if(i is even)
checkdigit += chr2int(s[i]) * 2;
else
checkdigit += chr2int(s[i]);
它们
for(i from s.length-1 to 0)
checkdigit += chr2int(s[i]);
仍然可以用 mod
操作终止,以使校验位适合一个字符
return int2chr( chr2int('a') + (checkdigit mod 25) );
< em>作为这个问题的旁注,可能对 Luhn 算法的图形表示感兴趣,这使得它更容易理解:
其实这个是原始的Luhn算法,甚至不需要使用MOD函数。
Do you know why the Luhn mod N algoritm in order to create the check digit performs a sum by doubling the value of each even placed char instead of perfoming a simple sum of all chars?
In pseudo-code words:
given:
var s = "some string i want to create check digit";
do you know why Luhn mod N does basically this:
for(i from s.length-1 to 0)
if(i is even)
checkdigit += chr2int(s[i]) * 2;
else
checkdigit += chr2int(s[i]);
instead of simply doing a sum
for(i from s.length-1 to 0)
checkdigit += chr2int(s[i]);
they can still both terminate with a mod
operation to make the checkdigit fit into one char
return int2chr( chr2int('a') + (checkdigit mod 25) );
As a side note to this question, to whom it may be interested in a graphic representation of the Luhn algorithm that makes it even more simple to understand:
Actually this one is the original Luhn algorithm that does not even needs to use MOD function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
校验数字字符旨在防止输入意外损坏,例如当职员通过键盘输入数字时。
如果仅使用总和,则字符串“ABCD”和“ABDC”将产生相同的校验和(“A”+“B”+“C”+“D”),因此可能会发生简单的交换错误而不会被注意到。
但是,考虑到奇偶性,“ABCD”和“ABDC”将变为 (2"A" + "B" + 2"C" + "D") 和 (2"A" + "B" + 2"D" +“C”),它们(可能)是不同的数字,因此通过这种方式我们可以检测两个字符是否无意中交换。
Checkdigit characters are designed to prevent accidental mangling of an input, for example when a clerk enters the number via keyboard.
If just a sum is used both strings "ABCD" and "ABDC" would yield the same checksum ("A" + "B" + "C" + "D"), so simple swap errors could happen unnoticed.
However, taking parity into consideration, "ABCD" and "ABDC" will become (2"A" + "B" + 2"C" + "D") and (2"A" + "B" + 2"D" + "C") respectively, which are (likely) different numbers, so in this way we could detect if two characters were inadvertently swapped.