2021-08-28 各种 hex 校验 ,加总异或校验,总加和校验 ,16 CRC 低字节在前,16 CRC 高字节在前,8 CRC,32 CRC 低字节在前,32 CRC 高字节在前

def uchar_checksum_CRC(input_str, byteorder='little'):
    """
    总加和校验
    @param input_str: 总加和校验
    @param byteorder: 大/小端
    """
    try:
        data = hex_str(input_str)
        length = len(data)
        checksum = 0
        for i in range(0, length):
            checksum += int.from_bytes(data[i:i + 1], byteorder, signed=False)
            checksum &= 0xFF  # 强制截断

        x_str = input_str + " " + str(('%0#4x' % (checksum,))[2:])
        return x_str.upper()
    except Exception as e:
        print('uchar_checksum_CRC: ',e)
        return None



def calc_chksums_CRC(input_s_):
    """ 加总异或校验 """
    try:
        checksum = 0
        data = hex_str(input_s_)
        for el in data:
            checksum ^= (el)
            #checksum ^= ord(el)
        # print (checksum, hex(checksum), chr(checksum))
        R_data = input_s_ + ' ' + str(('%0#4x' % (checksum,))[2:])
        return R_data.upper()

    except Exception as e:
        print("calc_chksums_CRC: ",e)
        return None



def crc16_modbus_crc(s):
    """ 16 CRC 低字节在前  CRC16/MODBUS"""

    def get_crc_value(s, crc16):
        """ 16 CRC 低字节在前  CRC16/MODBUS """
        try:
            data = s.replace(' ', '')
            crc_out = hex(crc16(unhexlify(data))).upper()
            str_list = list(crc_out)
            if len(str_list) == 5:
                str_list.insert(2, '0')  # 位数不足补0
            crc_data=''.join(str_list[2:]).upper()
            # crc_data[2:] + ' ' + crc_data[:2]
            return crc_data[2:] + crc_data[:2]
        except Exception as e:
            print('get_crc_value: ', e)
            return None
    try:
        crc16 = mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)
        #return get_crc_value(s, crc16)
        data_r = s + " " + get_crc_value(s, crc16)
        return data_r.upper()
    except Exception as e:
        print('crc16_modbus_crc: ',e)
        return None



def crc16_modbus_crc_high(s):
    """ 16 CRC 高字节在前  CRC16/MODBUS"""
    def get_crc_value_high(s, crc16):
        """ 16 CRC 高字节在前 """
        try:
            data=s.replace(' ', '')
            crc_out=hex(crc16(unhexlify(data))).upper()
            str_list=list(crc_out)
            if len(str_list) == 5:
                str_list.insert(2, '0')  # 位数不足补0
            crc_data=''.join(str_list[2:]).upper()
            # crc_data[2:] + ' ' + crc_data[:2]
            return crc_data[:2] + crc_data[2:]
        except Exception as e:
            print('get_crc_value_high: ', e)
            return None
    try:
        crc16 = mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)
        # return get_crc_value_high(s, crc16)
        data_r = s + " " + get_crc_value_high(s, crc16)
        return data_r.upper()
    except Exception as e:
        print('crc16_modbus_crc_high: ',e)
        return None



def crc_8_crc(CRC_8_str):
    """ 8 CRC CRC-8校验  # CRC-8 ,CRC-8/ITU, CRC-8/ROHC,CRC-8/MAXIM """
    try:
        crc8 = crcmod.predefined.Crc('crc-8')
        crc8.update(bytes().fromhex(CRC_8_str))
        #return (hex(crc8.crcValue))
        data_r = CRC_8_str + " " + str(('%0#4x' % (crc8.crcValue,))[2:]) #(hex(crc8.crcValue))
        return data_r.upper()
    except Exception as e:
        print('crc_8_crc: ',e)
        return None

def crc_32_high_byte_crc(CRC_32_str):
    """ CRC-32高字节在前 ,CRC-8/ITU, CRC-8/ROHC,CRC-8/MAXIM """
    try:
        crc32 = crcmod.predefined.Crc('crc-32')
        crc32.update(bytes().fromhex(CRC_32_str))
        data_r = CRC_32_str + " " + str(('%0#10x' % (crc32.crcValue,))[2:]) #(hex(crc8.crcValue))
        return data_r.upper()
    except Exception as e:
        print('crc_32_high_byte_crc: ',e)
        return None


def crc_32_low_byte_crc(CRC_32_str):
    """ CRC-32低字节在前  ,CRC-8/ITU, CRC-8/ROHC,CRC-8/MAXIM """
    try:
        crc32 = crcmod.predefined.Crc('crc-32')
        crc32.update(bytes().fromhex(CRC_32_str))
        crc32_s = str(('%0#10x' % (crc32.crcValue,))[2:])  #D88D2B5E
        crc32_str = (crc32_s[-2:]) + (crc32_s[4:6])  + (crc32_s[2:4]) + (crc32_s[0:2])
        data_r = CRC_32_str + " " + crc32_str  #(hex(crc8.crcValue))
        return data_r.upper()
    except Exception as e:
        print('crc_32_low_byte_crc: ',e)
        return None



def hex_str(input_str):
    """# hex发送"""
    try:
        input_s = input_str.strip()
        send_list = []
        while input_s != '':
            try:
                num = int(input_s[0:2], 16)
            except ValueError:
                return None
            input_s = input_s[2:].strip()
            send_list.append(num)
        input_s_2 = bytes(send_list)
        # print(input_s_2)
        return input_s_2
    except Exception as e:
        print('hex_str: ',e)
        return None

if __name__ == '__main__':
    # http://www.metools.info/code/c15.html 在线编码网站
    input_s_3 = 'FA 06 D0 20 01 06 00 00 F7 EE DC B8 70 E0 C0 80'
    print("加总异或校验: ",calc_chksums_CRC(input_s_3))
    print("总加和校验: ",uchar_checksum_CRC(input_s_3))
    print("16 CRC 低字节在前: ",crc16_modbus_crc(input_s_3))
    print("16 CRC 高字节在前: ",crc16_modbus_crc_high(input_s_3))
    print("8 CRC: ",crc_8_crc(input_s_3))
    print("32 CRC 低字节在前: ", crc_32_low_byte_crc(input_s_3))
    print("32 CRC 高字节在前: ", crc_32_high_byte_crc(input_s_3))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值