From 451904a0c5fae3bd28d35c7128df3a9db1a04b26 Mon Sep 17 00:00:00 2001 From: jaseg Date: Thu, 26 Nov 2020 12:38:52 +0100 Subject: Add CRC32 implementation --- prototype/fw/src/crc32.c | 35 +++++++++++++++++++++++++++++++++++ prototype/fw/src/crc32.h | 12 ++++++++++++ prototype/fw/src/crc32_test.c | 20 ++++++++++++++++++++ 3 files changed, 67 insertions(+) create mode 100644 prototype/fw/src/crc32.c create mode 100644 prototype/fw/src/crc32.h create mode 100644 prototype/fw/src/crc32_test.c (limited to 'prototype/fw/src') diff --git a/prototype/fw/src/crc32.c b/prototype/fw/src/crc32.c new file mode 100644 index 0000000..4b03fbb --- /dev/null +++ b/prototype/fw/src/crc32.c @@ -0,0 +1,35 @@ +#include "crc32.h" +#include + +/* Polynomial: 0xEDB88320 */ + +/* python3: + * In [26]: apply = lambda st: ((st>>1) ^ 0xEDB88320) if (st & 1) else (st>>1) + * In [27]: print(',\n'.join([ '0x{:08x}'.format(apply(apply(apply(apply(x))))) for x in range(16) ])) + */ +uint32_t crc32_table[16] = { + 0x00000000, + 0x1db71064, + 0x3b6e20c8, + 0x26d930ac, + 0x76dc4190, + 0x6b6b51f4, + 0x4db26158, + 0x5005713c, + 0xedb88320, + 0xf00f9344, + 0xd6d6a3e8, + 0xcb61b38c, + 0x9b64c2b0, + 0x86d3d2d4, + 0xa00ae278, + 0xbdbdf21c +}; + +crc32_t crc32_update(crc32_t state, uint8_t c) +{ + state ^= c; + state = (state>>4) ^ crc32_table[state&0xf]; + state = (state>>4) ^ crc32_table[state&0xf]; + return state; +} diff --git a/prototype/fw/src/crc32.h b/prototype/fw/src/crc32.h new file mode 100644 index 0000000..7a3a729 --- /dev/null +++ b/prototype/fw/src/crc32.h @@ -0,0 +1,12 @@ +#ifndef __CRC_32_H__ +#define __CRC_32_H__ + +#include + +typedef uint32_t crc32_t; + +inline static uint32_t crc32_reset() { return ~0; } +uint32_t crc32_update(uint32_t old_state, uint8_t c); +inline static uint32_t crc32_finalize(uint32_t state) { return ~state; } + +#endif /* __CRC_32_H__ */ diff --git a/prototype/fw/src/crc32_test.c b/prototype/fw/src/crc32_test.c new file mode 100644 index 0000000..e23bb37 --- /dev/null +++ b/prototype/fw/src/crc32_test.c @@ -0,0 +1,20 @@ + +#include + +#include "crc32.h" + +int main(void) { + crc32_t state = crc32_reset(); + + do { + char c; + if (fread(&c, 1, 1, stdin) != 1) + break; + + state = crc32_update(state, (uint8_t)c); + } while(23); + + state = crc32_finalize(state); + printf("%08x\n", state); + return 0; +} -- cgit