Coverage for tropicsquare / crc.py: 100%

20 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-03-27 21:24 +0000

1# Implement CRC16 checksum 

2 

3class CRC: 

4 CRC16_POLYNOMIAL = 0x8005 

5 CRC16_INITIAL_VAL = 0x0000 

6 CRC16_FINAL_XOR_VALUE = 0x0000 

7 

8 

9 @classmethod 

10 def crc16(cls, data: bytes) -> bytes: 

11 """Compute the CRC16 value for the given byte sequence.""" 

12 crc = cls.CRC16_INITIAL_VAL 

13 for byte in data: 

14 crc = cls._crc16_byte(byte, crc) 

15 crc ^= cls.CRC16_FINAL_XOR_VALUE 

16 

17 return bytes([crc & 0xFF, (crc >> 8) & 0xFF]) 

18 

19 

20 @classmethod 

21 def _crc16_byte(cls, data: int, crc: int) -> int: 

22 """Process one byte of data into the CRC.""" 

23 crc ^= data << 8 

24 for _ in range(8): 

25 if crc & 0x8000: 

26 crc = (crc << 1) ^ cls.CRC16_POLYNOMIAL 

27 else: 

28 crc <<= 1 

29 crc &= 0xFFFF 

30 return crc