summaryrefslogtreecommitdiff
path: root/src/lib/crc8.c
diff options
context:
space:
mode:
authorDimitri Staessens <dimitri@ouroboros.rocks>2026-04-26 07:38:43 +0200
committerSander Vrijders <sander@ouroboros.rocks>2026-05-06 09:04:48 +0200
commit964c26eb326dc26c032a3ccba10cb6d376bb3cf4 (patch)
tree1bf4a80f81f5d69afc17a4950248771d60aeb030 /src/lib/crc8.c
parent20d4a472800cbc9338f0c6c9c3dfce8eb13663c7 (diff)
downloadouroboros-964c26eb326dc26c032a3ccba10cb6d376bb3cf4.tar.gz
ouroboros-964c26eb326dc26c032a3ccba10cb6d376bb3cf4.zip
lib: Add CRC-8 and CRC-16 checksums
These checksum will be handy for header checksums. Signed-off-by: Dimitri Staessens <dimitri@ouroboros.rocks> Signed-off-by: Sander Vrijders <sander@ouroboros.rocks>
Diffstat (limited to 'src/lib/crc8.c')
-rw-r--r--src/lib/crc8.c64
1 files changed, 64 insertions, 0 deletions
diff --git a/src/lib/crc8.c b/src/lib/crc8.c
new file mode 100644
index 00000000..e8b9685a
--- /dev/null
+++ b/src/lib/crc8.c
@@ -0,0 +1,64 @@
+/*
+ * Ouroboros - Copyright (C) 2016 - 2026
+ *
+ * 8-bit Cyclic Redundancy Check (AUTOSAR variant)
+ *
+ * Dimitri Staessens <dimitri@ouroboros.rocks>
+ * Sander Vrijders <sander@ouroboros.rocks>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public License
+ * version 2.1 as published by the Free Software Foundation.
+ *
+ * This library 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
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., http://www.fsf.org/about/contact/.
+ */
+
+/*
+ * CRC-8/AUTOSAR (reveng catalog):
+ * poly = 0x2f
+ * init = 0xff
+ * refin = false
+ * refout = false
+ * xorout = 0xff
+ * check = crc8_autosar("123456789") == 0xdf
+ */
+
+#include "config.h"
+
+#include <ouroboros/crc8.h>
+
+/* Bit-by-bit MSB-first CRC. The expected use case is header check
+ * sequences of a handful of bytes; a 256-byte lookup table would not
+ * pay for the extra .rodata footprint at typical input sizes.
+ */
+void crc8_autosar(uint8_t * crc,
+ const void * buf,
+ size_t len)
+{
+ const uint8_t * p;
+ uint8_t c;
+ size_t n;
+ int i;
+
+ p = (const uint8_t *) buf;
+ c = *crc ^ 0xff;
+
+ for (n = 0; n < len; n++) {
+ c ^= p[n];
+ for (i = 0; i < 8; i++) {
+ if (c & 0x80)
+ c = (uint8_t) ((c << 1) ^ 0x2f);
+ else
+ c = (uint8_t) (c << 1);
+ }
+ }
+
+ *crc = c ^ 0xff;
+}