简体   繁体   English

C 将 20 位字符串转换为数字以进行 IBAN 验证

[英]C converting 20 digit string to number for IBAN validation

I am doing an IBAN validation in C.我正在 C 中进行 IBAN 验证。 For this I have a char* which is something like '2012129431327715102998'.为此,我有一个 char*,类似于“2012129431327715102998”。 Now I want to check the IBAN by taken the value modulo 97. So I want to do 2012129431327715102998 % 97 .现在我想通过取模 97 的值来检查 IBAN。所以我想做2012129431327715102998 % 97 I have already tried to convert the char* with strtoull but this gives me an out-of-range error.我已经尝试使用 strtoull 转换 char* ,但这给了我一个超出范围的错误。 So my question is: How can I convert this char* to a number where I can do a modulo calculation?所以我的问题是:如何将此 char* 转换为可以进行模计算的数字? Thanks in advance提前致谢

A simple way without using additional library is to remember that mathematically : mod(a*b, c) == mod(b * mod(a, c), c) .一个不使用额外库的简单方法是在数学上记住: mod(a*b, c) == mod(b * mod(a, c), c) So you can process the number in chunks :因此,您可以分处理数字:

// suitable for a 32 bits system, can use 8 for a 64 bits one
#define NB 4
/*********************
 * Initial is a string containin only digits representing an arbitrary large number
 * div in a number < 10000 (because NB is 4)
 * ******************/
int large_mod(char *initial, int div) {
    char old[1 + (NB * 2)] = "";   // enough room for a remainder and next chunk
    long val;
    for (unsigned i=0; i<strlen(initial); i+= NB) {
        strncat(old, initial + i, NB);   // add the new chunk
        val = atol(old) % div;           // compute the remainder
        sprintf(old, "%ld", val);        // keep it for next chunk
        // printf("%ld ", val);          // uncomment for debugging
    }
    return (int) val;
}

For 2012129431327715102998 % 97, it gives as expected 53.对于 2012129431327715102998 % 97,它给出了预期的 53。

You can write a custom function for this.您可以为此编写自定义 function。 Applying the modulo operator on partial sums, you can convert a number of arbitrary length:对部分和应用模运算符,您可以转换多个任意长度:

#include <stdio.h>

int mod97(const char *s) {
    int res = 0;
    while (*s >= '0' && *s <= '9') {
        res = (res * 10 + (*s++ - '0')) % 97;
    }
    return res;
}

int main(int argc, char *argv[]) {
    for (int i = 1; i < argc; i++) {
         printf("%s -> %d\n", argv[i], mod97(argv[i]));
    }
    return 0;
}

Output: Output:

./mod97 2012129431327715102998
2012129431327715102998 -> 53

This method is simpler and more generic than the one described in the wiki article: computing the modulo 97 of a large number can be achieved by splitting the number in chunks of 9 digits and combining the modulo of these chunks.这种方法比wiki文章中描述的方法更简单、更通用:计算一个大数的模 97 可以通过将数字分成 9 位的块并组合这些块的模来实现。 This splitting is specific to 97 and works because 1000000000 % 97 == 1 .这种拆分特定于97并且有效,因为1000000000 % 97 == 1 The above method works for any modulo value up to INT_MAX / 10 .上述方法适用于最大为INT_MAX / 10的任何模值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM