crc16_ccitt_bitwise_ref.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/env python3
  2. """Independent CRC-16/CCITT-FALSE reference, written bit by bit.
  3. This file exists to cross-check the generated golden vectors. It is a fresh
  4. implementation: it uses no lookup table, no nibble table and shares no code
  5. with ``tools/generate_6400_manual.py``, ``tools/generate_mrdimm_params.py`` or
  6. ``tools/crc16_ccitt_table.py`` (the generator path). An encoder that decodes
  7. its own output is not end-to-end evidence; these frames are computed twice by
  8. two structurally different implementations.
  9. Parameters: poly 0x1021, init 0xFFFF, refin/refout false, xorout 0.
  10. Coverage: TYPE, LENGTH and PAYLOAD; the ``A5 5A`` header is not covered.
  11. Wire order: low CRC byte first.
  12. """
  13. from __future__ import annotations
  14. from typing import Iterable
  15. PREAMBLE = b"\xA5\x5A"
  16. POLYNOMIAL = 0x1021
  17. INITIAL = 0xFFFF
  18. def crc16_ccitt_false_bitwise(data: bytes | bytearray | Iterable[int]) -> int:
  19. """MSB-first bit-at-a-time CRC-16/CCITT-FALSE."""
  20. crc = INITIAL
  21. for raw in data:
  22. crc ^= (int(raw) & 0xFF) << 8
  23. for _ in range(8):
  24. if crc & 0x8000:
  25. crc = ((crc << 1) ^ POLYNOMIAL) & 0xFFFF
  26. else:
  27. crc = (crc << 1) & 0xFFFF
  28. return crc
  29. def frame_bytes(frame_type: int, payload: bytes | bytearray = b"") -> bytes:
  30. """Build ``A5 5A | TYPE | LENGTH:u8 | PAYLOAD | CRC_L | CRC_H``."""
  31. body = bytes((frame_type & 0xFF, len(payload) & 0xFF)) + bytes(payload)
  32. crc = crc16_ccitt_false_bitwise(body)
  33. return PREAMBLE + body + crc.to_bytes(2, "little")
  34. def frame_hex(frame_type: int, payload: bytes | bytearray = b"") -> str:
  35. return frame_bytes(frame_type, payload).hex().upper()
  36. def verify_frame(frame: bytes | bytearray) -> bool:
  37. """True when a complete frame has the correct header, length and CRC."""
  38. data = bytes(frame)
  39. if len(data) < 6 or data[:2] != PREAMBLE:
  40. return False
  41. declared = data[3]
  42. if len(data) != declared + 6:
  43. return False
  44. expected = crc16_ccitt_false_bitwise(data[2:-2])
  45. return data[-2:] == expected.to_bytes(2, "little")