Skip to content

About

CRC-16 calculation for Modbus protocol

Resources

Stars

2 stars

Watchers

1 watching

Forks

Repository files navigation

Modbus CRC-16

License Downloads Latest Version Supported Python versions tests

CRC-16 calculation library for Modbus protocol. Tiny, dependency-free and fast: a single 256-entry lookup table, no runtime dependencies, type hints included.

Algorithm

The checksum is CRC-16/MODBUS:

Parameter Value
Width 16 bits
Polynomial 0x8005 (reflected: 0xA001)
Initial value 0xFFFF
Reflect in / out yes / yes
Final XOR 0x0000
Check ("123456789") 0x4B37, transmitted as b'\x37\x4B'
Byte order on wire low byte first

Installation

Install it with pip:

$ pip install modbus-crc

Or you can add it as dependency in requirements.txt file of your python application:

modbus-crc~=2.1.1

Usage

For signing byte package use add_crc:

from modbus_crc import add_crc

signed_package = add_crc(b'\x00\x12\x34\xAB\xCD\xEF')

Result is b'\x00\x12\x34\xAB\xCD\xEF\xD2\xD4'. For validation signed package use check_crc:

from modbus_crc import check_crc

if not check_crc(b'\x00\x12\x34\xAB\xCD\xEF\xD2\xD4'):
    raise SomeException()

To get the checksum alone (low byte first, exactly as it is transmitted on the wire), use crc16:

from modbus_crc import crc16

crc16(b'\x01\x03\x00\x00\x00\x0A')  # b'\xC5\xCD'

Here is a real Modbus RTU request — "read 10 holding registers from slave 1":

add_crc(b'\x01\x03\x00\x00\x00\x0A')  # b'\x01\x03\x00\x00\x00\x0A\xC5\xCD'

check_crc validates the whole signed frame, so it works with data read straight from the serial port, without splitting off the trailing bytes:

check_crc(b'\x01\x03\x00\x00\x00\x0A\xC5\xCD')  # True
check_crc(b'\x01\x03\x00\x00\x00\x0A\xC5\xCE')  # False

API

All three functions accept bytes, bytearray and memoryview. That union is exported as BytesLike, so annotations written against the package do not have to repeat it.

Function Returns Description
crc16(data) bytes 2-byte checksum of data, low byte first
add_crc(package) bytes package with the checksum appended; input type is normalized
check_crc(package) bool True if package carries a valid trailing checksum

Notes:

  • add_crc always returns bytes, even for bytearray and memoryview input.
  • Input is always read as raw bytes. A memoryview over an array of wider items, a strided slice or a non-contiguous view contributes the bytes it lays out, not its elements, so crc16, add_crc and check_crc never disagree on the same object.
  • Anything that is not bytes-like (int, str, None, lists) raises TypeError.
  • check_crc(b'') is False: an empty package has no valid checksum.
  • Functions are pure: they keep no state between calls. The lookup table is built once, at import time.

Compatibility

  • Python 3.9 and newer, including free-threaded builds: CI runs every version from 3.9 to 3.15 plus the free-threaded 3.13t.
  • No runtime dependencies.
  • Type hints are shipped with the package (py.typed, PEP 561), so mypy and pyright see real signatures instead of Any.

Development

$ python -m venv .venv
$ .venv\Scripts\activate          # Windows; on POSIX: source .venv/bin/activate
$ pip install -e ".[dev]"          # installs the package and pytest
$ python -m pytest

The test suite covers:

  • canonical Modbus frames with published checksums,
  • an independent bit-by-bit implementation written from the specification, used as an oracle against the fast table-driven code: all 256 one-byte and all 65 536 two-byte inputs, plus random payloads up to 1 KiB,
  • edge cases: empty package, one-byte packages, bytearray / memoryview / array input, wide-item and strided views, TypeError for anything that is not bytes-like,
  • detection of every single-byte corruption (all 255 masks at every byte position) of a signed frame.

python benchmarks/benchmark_crc.py compares the current implementation with the previous one and reports throughput and the speed ratio for the interpreter that runs it.

Project layout:

modbus_crc/__init__.py    the whole library
tests/test_modbus_crc.py  test suite
benchmarks/               speed comparison with the previous implementation
pyproject.toml            metadata, build config and pytest settings
.github/workflows/        CI: tests on Python 3.9-3.15 and 3.13t, release pipeline

To build and verify a release:

$ pip install build twine
$ python -m build
$ python -m twine check dist/*

Changelog

See CHANGELOG.md. GitHub Releases are generated from the matching entry of that file, so the history is available both in git and on the releases page.

License

Distributed under the BSD 3-Clause license. See LICENSE.md for details.

About

CRC-16 calculation for Modbus protocol

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages