"""Bit-at-a-time CRC model in the parametrised (Rocksoft/RevEng) form. Parameters follow the RevEng catalogue: width, poly, init, refin, refout, xorout. """ from __future__ import annotations from dataclasses import dataclass @dataclass(frozen=True) class CrcSpec: name: str width: int poly: int init: int refin: bool refout: bool xorout: int check: int # CRC of the ASCII string "123456789" # Values copied from the RevEng CRC catalogue (reveng.sourceforge.io/crc-catalogue/). CRC8_SMBUS = CrcSpec("CRC-8/SMBUS", 8, 0x07, 0x00, False, False, 0x00, 0xF4) CRC16_IBM3740 = CrcSpec("CRC-16/IBM-3740", 16, 0x1021, 0xFFFF, False, False, 0x0000, 0x29B1) CRC16_XMODEM = CrcSpec("CRC-16/XMODEM", 16, 0x1021, 0x0000, False, False, 0x0000, 0x31C3) CRC16_KERMIT = CrcSpec("CRC-16/KERMIT", 16, 0x1021, 0x0000, True, True, 0x0000, 0x2189) CRC32_ISOHDLC = CrcSpec("CRC-32/ISO-HDLC", 32, 0x04C11DB7, 0xFFFFFFFF, True, True, 0xFFFFFFFF, 0xCBF43926) ALL = (CRC8_SMBUS, CRC16_IBM3740, CRC16_XMODEM, CRC16_KERMIT, CRC32_ISOHDLC) def reflect(value: int, bits: int) -> int: out = 0 for i in range(bits): if value >> i & 1: out |= 1 << (bits - 1 - i) return out def crc_update_byte(reg: int, byte: int, spec: CrcSpec) -> int: """Shift one byte into the (unreflected) register, MSB first.""" if spec.refin: byte = reflect(byte, 8) top = 1 << (spec.width - 1) mask = (1 << spec.width) - 1 for i in range(7, -1, -1): fb = bool(reg & top) ^ bool(byte >> i & 1) reg = (reg << 1) & mask if fb: reg ^= spec.poly return reg def crc_finish(reg: int, spec: CrcSpec) -> int: if spec.refout: reg = reflect(reg, spec.width) return reg ^ spec.xorout def crc(data: bytes, spec: CrcSpec) -> int: reg = spec.init for b in data: reg = crc_update_byte(reg, b, spec) return crc_finish(reg, spec) if __name__ == "__main__": for s in ALL: print(f"{s.name:16s} check 0x{crc(b'123456789', s):0{s.width // 4}X}")