ctype-conversioniban

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


Solution

  • 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.