Code: Select all
def make_crc_table():
poly = 0x8408
table = []
for byte in range(256):
crc = 0
for bit in range(8):
if (byte ^ crc) & 1:
crc = (crc >> 1) ^ poly
else:
crc >>= 1
byte >>= 1
table.append(crc)
return table
table = make_crc_table()
def crc_16_fast(msg):
crc = 0xffff
for byte in msg:
crc = table[(byte ^ crc) & 0xff] ^ (crc >> 8)
return crc ^ 0xffff
# Test
msg = bytearray(b'x' * 1024)
t0 = time.monotonic_ns()
n = 100
for _ in range(n):
crc_16_fast(msg)
print((time.monotonic_ns()- t0) / n / 1e6, 'ms')