crc 循环冗余校验


CRC16 python实现

crc16_IBM

def crc16_IBM(data):
    # parameter data :'01 00 00 80 00 00 00 ..... 00 ce c2 b6 c8 33 38 32 35 a1 e6'
    if isinstance(data, str):
        data = data.strip().split(' ')
        crc = 0x0
        for i in range(len(data)):
            crc = ((int(data[i], base=16) & 0xFF) ^ crc)
            for j in range(8):
                if (crc & 0x1) == 1:
                    crc = (crc >> 1) ^ 0xa001
                else:
                    crc >>= 1
        res = hex(crc)[2:]
        if len(res) < 4:
            res = (4 - len(res)) * '0' + res

        return [res[2:], res[:2]]

环境212数据报字符串循环冗余校验

def crc16(text):
    """
    向服务器发送数据报字符串的循环冗余校验
    hj 212-2017 crc16效验
    :param text: 待效验的字符串
    :return: result
    """
    data = bytearray(text, encoding='utf-8')
    crc = 0xffff
    dxs = 0xa001
    for i in range(len(data)):
        hibyte = crc >> 8
        crc = hibyte ^ data[i]
        for j in range(8):
            sbit = crc & 0x0001
            crc = crc >> 1
            if sbit == 1:
                crc ^= dxs
    res = str(hex(crc)[2:]).upper()
    if len(res) < 4:
        res = (4 - len(res)) * '0' + res

    return res