From ff1289c03d7390364b5ab841e7dae0cb40ef6efe Mon Sep 17 00:00:00 2001 From: douniwan5788 Date: Sat, 15 Mar 2025 04:18:41 +0800 Subject: [PATCH] Update Crc16 function to use bitlength instead of length --- common/crc16.c | 13 +++++++++---- common/crc16.h | 2 +- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/common/crc16.c b/common/crc16.c index 812cd3481..e55b20bdc 100644 --- a/common/crc16.c +++ b/common/crc16.c @@ -142,12 +142,17 @@ uint16_t update_crc16(uint16_t crc, uint8_t c) { } // two ways. msb or lsb loop. -uint16_t Crc16(uint8_t const *d, size_t length, uint16_t remainder, uint16_t polynomial, bool refin, bool refout) { - if (length == 0) +uint16_t Crc16(uint8_t const *d, size_t bitlength, uint16_t remainder, uint16_t polynomial, bool refin, bool refout) { + if (bitlength == 0) return (~remainder); - for (uint32_t i = 0; i < length; ++i) { - uint8_t c = d[i]; + uint8_t offset = 8 - (bitlength % 8); + // front padding with 0s won't change the CRC result + uint8_t prebits = 0; + for (uint32_t i = 0; i < (bitlength + 7) / 8; ++i) { + uint8_t c = prebits | d[i] >> offset; + prebits = d[i] << (8 - offset); + if (refin) c = reflect8(c); // xor in at msb diff --git a/common/crc16.h b/common/crc16.h index 80758d95b..c8aecaf21 100644 --- a/common/crc16.h +++ b/common/crc16.h @@ -47,7 +47,7 @@ typedef enum { uint16_t update_crc16_ex(uint16_t crc, uint8_t c, uint16_t polynomial); uint16_t update_crc16(uint16_t crc, uint8_t c); -uint16_t Crc16(uint8_t const *d, size_t length, uint16_t remainder, uint16_t polynomial, bool refin, bool refout); +uint16_t Crc16(uint8_t const *d, size_t bitlength, uint16_t remainder, uint16_t polynomial, bool refin, bool refout); uint16_t Crc16ex(CrcType_t ct, const uint8_t *d, size_t n); void compute_crc(CrcType_t ct, const uint8_t *d, size_t n, uint8_t *first, uint8_t *second);