Python CRC16校验算法

时间:2022-09-17 21:34:32
def crc16(x, invert):
a = 0xFFFF
b = 0xA001
for byte in x:
a ^= ord(byte)
for i in range(8):
last = a % 2
a >>= 1
if last == 1:
a ^= b
s = hex(a).upper() return s[4:6]+s[2:4] if invert == True else s[2:4]+s[4:6]

示例:

print(crc16("012345678", True))
print(crc16("012345678", False))
print(crc16("010600010017", True))

计算结果:

Python CRC16校验算法