#include #include /* * Calculates CCITT 16-bit CRC * * Copyright (c) 2022 - 2023 R.J. van der Putten, Leiden, Holland, * rob at sput dot nl. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ int main(void) { char line[4096]; int i, j, len; unsigned int c, poly, shft; c = 0; i = 0; j = 0; len = 0; shft = 0; memset(line, 0, 4096); /* * Calculate CCITT 16-bit CRC * * 16 12 5 * X + X + X + 1 * * 17 bits * * 6 5432 1098 7654 3210 * 1 0001 0000 0010 0001 * 1 1 0 2 1 */ poly = 0x11021; while (fgets(line, 4088, stdin)) { i = 0; /* Cleanup */ len = strlen(line) - 1; if (line[len] == 10) { line[len] = 0; len--; } if (line[len] == 13) { line[len] = 0; len--; } len++; /* Pad for length of CRC */ line[len] = 0; len++; line[len] = 0; len++; shft = 0xFFFF; while (i < len) { c = (unsigned int) ((unsigned char) line[i]); j = 0; while (j < 8) { shft = shft << 1; /* 1st time this is 1FFFE */ if ((c & 0x80) != 0) { /* Data msb is one; make shft lsb one */ shft = shft | 1; } c = c << 1; if ((shft & 0x10000) != 0) { /* 1 xxxx xxxx xxxx xxxx */ shft = shft ^ poly; } j++; } i++; } printf("%04X\n", shft); } return(0); }