commit d288884d5c590400d18c23d0fb6839cfd6112d5a
parent f3fdc205176881e8c2cb70fa29cdb14d4e9711ef
Author: Henry Wilson <henry@henryandlizzy.uk>
Date: Sat, 26 Aug 2023 17:42:57 +0100
damm-checksum: Add checksumming program example
Diffstat:
1 file changed, 58 insertions(+), 0 deletions(-)
diff --git a/src/damm-checksum.c b/src/damm-checksum.c
@@ -0,0 +1,58 @@
+#include <stdio.h>
+#include <ctype.h>
+#include <stdlib.h>
+#include <string.h>
+
+char damm_sum(char const* const str)
+{
+ static char const lookup[100] = {
+ 0, 3, 1, 7, 5, 9, 8, 6, 4, 2,
+ 7, 0, 9, 2, 1, 5, 4, 8, 6, 3,
+ 4, 2, 0, 6, 8, 7, 1, 3, 5, 9,
+ 1, 7, 5, 0, 9, 8, 3, 4, 2, 6,
+ 6, 1, 2, 3, 0, 4, 5, 9, 7, 8,
+ 3, 6, 7, 4, 2, 0, 9, 5, 8, 1,
+ 5, 8, 6, 9, 7, 2, 0, 1, 3, 4,
+ 8, 9, 4, 5, 3, 6, 2, 0, 1, 7,
+ 9, 4, 3, 8, 6, 1, 7, 2, 0, 5,
+ 2, 5, 8, 1, 4, 3, 6, 7, 9, 0,
+ };
+ int last = 0;
+ char const* c = str;
+
+ while (isdigit(*c))
+ last = lookup[*c++ - '0' + last * 10];
+
+ if (!*c)
+ return last + '0';
+
+ dprintf(2, "'%s' must contain only digits\n", str);
+ exit(1);
+}
+
+void damm_append(char const* str)
+{
+ printf("%s%c\n", str, damm_sum(str));
+}
+
+int damm_check(char const* str)
+{
+ return damm_sum(str) == '0';
+}
+
+int main(int, char* argv[])
+{
+ ++argv;
+
+ for (/**/; *argv; ++argv)
+ {
+ if (!strcmp(*argv, "-c"))
+ {
+ ++argv;
+ break;
+ }
+ damm_append(*argv);
+ }
+ for (/**/; *argv; ++argv)
+ printf("%s: %s\n", *argv, damm_check(*argv) ? "OK" : "BAD");
+}