Python CRC16校验算法

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校验算法_第1张图片

转载于:https://www.cnblogs.com/oukunqing/p/5822781.html

你可能感兴趣的:(Python CRC16校验算法)