校验位算法 Luhn mod N 与简单和

发布于 2024-10-30 03:38:17 字数 878 浏览 1 评论 0原文

你知道为什么 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 算法的图形表示感兴趣,这使得它更容易理解:

输入图片description here

其实这个是原始的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:

enter image description here

Actually this one is the original Luhn algorithm that does not even needs to use MOD function.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

巷雨优美回忆 2024-11-06 03:38:17

校验数字字符旨在防止输入意外损坏,例如当职员通过键盘输入数字时。

如果仅使用总和,则字符串“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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文