CRCmod
CRCmod is a Python module for calculating Cyclic Redundancy Checks (CRCs). It provides functionality to generate custom CRC algorithms and access a wide range of predefined CRC algorithms, such as CRC-CCITT and CRC-32. The current version is 1.7. The library has a slow release cadence, with updates primarily focused on bug fixes and stability.
Warnings
- gotcha Input data to CRC functions (e.g., `update`, `mkCrcFun`) MUST be bytes (`bytes`), not strings (`str`). Passing a Python string will result in a `TypeError`.
- gotcha There are different ways to use crcmod: `crcmod.predefined.Crc` (object-oriented for standard CRCs), `crcmod.mkCrcFun` (functional for custom CRCs), and `crcmod.predefined.mkCrcFun` (functional for standard CRCs). Confusing these can lead to errors.
Install
-
pip install crcmod
Imports
- crcmod
import crcmod
- Crc
from crcmod.predefined import Crc
- mkCrcFun
from crcmod import mkCrcFun
Quickstart
import crcmod
import crcmod.predefined
# 1. Using a predefined CRC algorithm (object-oriented approach)
# Get a CRC-16-CCITT-FALSE calculator
crc16_ccitt = crcmod.predefined.Crc('crc-ccitt-false')
data_bytes = b'Hello, world!'
crc16_ccitt.update(data_bytes)
print(f"CRC-16-CCITT-FALSE for '{data_bytes.decode()}': {hex(crc16_ccitt.crcValue)}")
# You can reset and reuse the object
crc16_ccitt.reset()
crc16_ccitt.update(b'Another test')
print(f"CRC-16-CCITT-FALSE for 'Another test': {hex(crc16_ccitt.crcValue)}")
# 2. Creating a custom CRC function (functional approach)
# Example: CRC-32 (Ethernet) - polynomial 0x104C11DB7, initial 0xFFFFFFFF, xorOut 0xFFFFFFFF, revIn/Out True
crc32_func = crcmod.mkCrcFun(0x104C11DB7, initCrc=0xFFFFFFFF, xorOut=0xFFFFFFFF, rev=True)
data_bytes_32 = b'123456789'
result_32 = crc32_func(data_bytes_32)
print(f"CRC-32 for '{data_bytes_32.decode()}': {hex(result_32)}")
# 3. Using a predefined CRC algorithm (functional approach)
crc32_predef_func = crcmod.predefined.mkCrcFun('crc-32')
result_predef_32 = crc32_predef_func(b'123456789')
print(f"CRC-32 (predefined func) for '123456789': {hex(result_predef_32)}")