简体   繁体   中英

C converting 20 digit string to number for IBAN validation

I am doing an IBAN validation in C. For this I have a char* which is something like '2012129431327715102998'. Now I want to check the IBAN by taken the value modulo 97. So I want to do 2012129431327715102998 % 97 . I have already tried to convert the char* with strtoull but this gives me an out-of-range error. So my question is: How can I convert this char* to a number where I can do a modulo calculation? 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) . 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.

You can write a custom function for this. 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:

./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. This splitting is specific to 97 and works because 1000000000 % 97 == 1 . The above method works for any modulo value up to INT_MAX / 10 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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