Check Digit calculation (IBAN) - MOD 97

{ Posted on Apr 17 2009 by admin }
Tags : , ,
Categories : Programming

Some times I am amused how problems, that looked like huge pain, can be solved in few lines of code using basic math algorithms learned at elementary school. We were adding IBAN number verification which requires mod 97 calculation on number with 18 digits or more. First instinct was to just execute it directly as n%97Then it became clear that integer variable can’t be used. Than I start thinking about some other type or class, that can be magically used instead, but that just didn’t seemed as right way to go. OK, I had to think it over. Solution that I come up is using a “traditional long division algorithm”:

94 / 7 = 13 R 3
7
--------
24
21
--------
3

So here it is simple and efficient, c# code, but can easily be adapted for any programming language:

string str_digits = "12345678901234567890";
long mod_value = 0;
for (int i = 0; i < str_digits.Length; i++)
{
    long digit = str_digits[i] - '0';
    mod_value = ((mod_value * 10) + digit) % 97;
}

Post a Comment