From 6b82ddcd740fd3848e6fcea03411d5f3b46c62b6 Mon Sep 17 00:00:00 2001 From: ju6ge Date: Wed, 25 Mar 2026 13:54:20 +0100 Subject: [PATCH] updated crc algorithm to a more efficient implementation --- lib-bms-protocol/src/types.rs | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/lib-bms-protocol/src/types.rs b/lib-bms-protocol/src/types.rs index 79d558d..d3d0bc1 100644 --- a/lib-bms-protocol/src/types.rs +++ b/lib-bms-protocol/src/types.rs @@ -332,7 +332,7 @@ pub fn check_hemming(data: u32, hemming: u8) -> Result<(), HemmingCorrectionValu /// CRC-6 calculation using polynomial 0x21 (MSB first) /// -/// This function calculates a 6-bit CRC for 26 bits of data. +/// This function calculates a 6-bit CRC for a u32 value. /// The polynomial used is 0x21 in the crc world polynoms /// are named after the bit pattern with implicit assumption /// of the trailing 1, thus 0x21 become 0x43 referring to @@ -349,18 +349,15 @@ pub fn check_hemming(data: u32, hemming: u8) -> Result<(), HemmingCorrectionValu /// - All double-bit errors /// - Random errors with a probability of 2^-6 = 0.015625 of going undetected pub fn calc_crc6(data: u32) -> u8 { - let mut working_data: u32 = data << 6; - let mut polynom: u32 = 0x43 << 25; - let mut mask: u32 = 0x40 << 25; - while working_data >= 0x40 { - if working_data & mask != 0 { - working_data ^= polynom; + let mut crc: u8 = 0x00; + for pos in 0..32 { + if ((data >> (31-pos)) & 0x1) ^ ((crc >> 5) & 0x1) as u32 != 0 { + crc = ((crc << 1) ^ 0x03) & 0x3F; } else { - polynom >>= 1; - mask >>= 1; + crc = (crc << 1) & 0x3F; } } - (working_data & 0x3f) as u8 + crc } /// CRC-6 checking