/* * calculate check digit according to the LUHN formula. * Give it a full credit card number, including the check digit, * and it returns the number you add to the check digit to make * it right. Now, really, there are two ways to call this. * 1. Append a zero, and let it tell you what the check digit * should have been. * 2. give it the full credit card number, and it returns * zero if the check digit is correct, non-zero otherwise. */ #include int checkdig(const char *buf) { int i, l; int sum; l = strlen(buf); for (i = l - 2, sum = 0; i >= 0; --i) { sum += ((l - i) % 2 ? "0123456789" : "0246813579") [buf[i]-'0'] - '0'; } sum = (10 - sum % 10) % 10; return (sum + '0') - buf[l - 1]; } #define TEST 1 #ifdef TEST #include int main(int ac, char **av) { int i; for (i = 1; i < ac; ++i) { printf("checkdig returns %d\n", checkdig(av[i])); } return 0; } #endif