我想在OCR的帮助下读取大约16-20个字符(A-Z,0-9)的序列号。因为每次我想在序列号中添加一个校验字符时,所有字符都无法正确识别。 目前我找到了简单的Luhn mod N算法(Wikipedia)。这个算法对于换位错误不安全(09 => 90)。
Wikipedia的实施:
char GenerateCheckCharacter(string input) {
int factor = 2;
int sum = 0;
int n = NumberOfValidInputCharacters();
// Starting from the right and working leftwards is easier since
// the initial "factor" will always be "2"
**//int index = 0;**
for (int i = input.Length - 1; i >= 0; i--) {
int codePoint = CodePointFromCharacter(input[i]);
int addend = factor * codePoint;
// Alternate the "factor" that each "codePoint" is multiplied by
factor = (factor == 2) ? 1 : 2;
**//factor = index;**
// Sum the digits of the "addend" as expressed in base "n"
addend = (addend / n) + (addend % n);
sum += addend;
**//index++;**
}
// Calculate the number that must be added to the "sum"
// to make it divisible by "n"
int remainder = sum % n;
int checkCodePoint = (n - remainder) % n;
return CharacterFromCodePoint(checkCodePoint);
}
NumberOfValidInputCharacters()将是36(A-Z,0-9)
但是如果我将“factor”变量修改为序列号内部字符的实际索引,那么它是否比以前更安全? (参见代码中的** **行)