crc16_ccitt_table.py 918 B

1234567891011121314151617181920212223242526
  1. """Independent CRC-16/CCITT-FALSE reference (nibble table, not bit-serial)."""
  2. from __future__ import annotations
  3. from typing import Iterable
  4. # High-nibble table for poly 0x1021, init 0xFFFF, no reflect, xorout 0.
  5. _NIBBLE = (
  6. 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
  7. 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
  8. )
  9. def crc16_ccitt_false_table(data: bytes | bytearray | Iterable[int]) -> int:
  10. crc = 0xFFFF
  11. for raw in data:
  12. value = int(raw) & 0xFF
  13. crc = ((crc << 4) & 0xFFFF) ^ _NIBBLE[((crc >> 12) ^ (value >> 4)) & 0x0F]
  14. crc = ((crc << 4) & 0xFFFF) ^ _NIBBLE[((crc >> 12) ^ value) & 0x0F]
  15. return crc
  16. def frame_bytes(frame_type: int, payload: bytes) -> bytes:
  17. body = bytes((frame_type & 0xFF, len(payload) & 0xFF)) + payload
  18. crc = crc16_ccitt_false_table(body)
  19. return b"\xA5\x5A" + body + crc.to_bytes(2, "little")