CRC-8 in Python for one byte (crcmod)

1.9k Views Asked by At

Hopefully a simple fix, but can't seem to find it.

I am using crcmod to calculate the CRC-8 with polynomial x^8 + x^2 + x + 1 (0x07).

import crcmod

crcPoly = 0b100000111     # x^8 + x^2 + x + 1 (Hex: 0x07)
buff = 0b01110001         # (Hex: 0x71)

CRC = crcmod.mkCrcFun(crcPoly)
crc = CRC(chr(buff).encode('utf-8'))
print(hex(crc))

This prints 0xa, but both CRC-8 Calc and arduino code, gives me 0x50.

Any suggestions much appreciated. Please keep it simple as evidently I am not sure with datatypes etc.

2

There are 2 best solutions below

0
Will Powell On

SOLVED USING CRC8:

from crc import CrcCalculator, Crc8

buff = [0b11011010] # (Hex: 0x71)

crc_calculator = CrcCalculator(Crc8.CCITT)
checksum = crc_calculator.calculate_checksum(buff)
print(hex(checksum))
0
Lrnt Gr On

It's because of the default values of parameters you are not providing to crcmod.mkCrcFun: see documentation.

By specifying the values of initCrc, rev and xorOut parameters, it works properly and outputs 0x50:

import crcmod

CRC = crcmod.mkCrcFun(
    poly=0b100000111,
    initCrc=0,
    rev=False,
    xorOut=0
)
crc = CRC(bytes([0b01110001]))
print(hex(crc))

Note that the CRC function you're trying to create already exists: it's crcmod.predefined.mkCrcFun('crc-8').