examples

Toy examples in single C files.
git clone git://henryandlizzy.uk/examples
Log | Files | Refs

damm-checksum.c (1065B)


      1 #include <stdio.h>
      2 #include <ctype.h>
      3 #include <stdlib.h>
      4 #include <string.h>
      5 
      6 char damm_sum(char const* const str)
      7 {
      8 	static char const lookup[100] = {
      9 		0, 3, 1, 7, 5, 9, 8, 6, 4, 2,
     10 		7, 0, 9, 2, 1, 5, 4, 8, 6, 3,
     11 		4, 2, 0, 6, 8, 7, 1, 3, 5, 9,
     12 		1, 7, 5, 0, 9, 8, 3, 4, 2, 6,
     13 		6, 1, 2, 3, 0, 4, 5, 9, 7, 8,
     14 		3, 6, 7, 4, 2, 0, 9, 5, 8, 1,
     15 		5, 8, 6, 9, 7, 2, 0, 1, 3, 4,
     16 		8, 9, 4, 5, 3, 6, 2, 0, 1, 7,
     17 		9, 4, 3, 8, 6, 1, 7, 2, 0, 5,
     18 		2, 5, 8, 1, 4, 3, 6, 7, 9, 0,
     19 	};
     20 	int last = 0;
     21 	char const* c = str;
     22 
     23 	while (isdigit(*c))
     24 		last = lookup[*c++ - '0' + last * 10];
     25 
     26 	if (!*c)
     27 		return last + '0';
     28 
     29 	dprintf(2, "'%s' must contain only digits\n", str);
     30 	exit(1);
     31 }
     32 
     33 void damm_append(char const* str)
     34 {
     35 	printf("%s%c\n", str, damm_sum(str));
     36 }
     37 
     38 int damm_check(char const* str)
     39 {
     40 	return damm_sum(str) == '0';
     41 }
     42 
     43 int main(int, char* argv[])
     44 {
     45 	++argv;
     46 
     47 	for (/**/; *argv; ++argv)
     48 	{
     49 		if (!strcmp(*argv, "-c"))
     50 		{
     51 			++argv;
     52 			break;
     53 		}
     54 		damm_append(*argv);
     55 	}
     56 	for (/**/; *argv; ++argv)
     57 		printf("%s: %s\n", *argv, damm_check(*argv) ? "OK" : "BAD");
     58 }