Python_CRC16-MODBUS校验

# -*- coding: utf-8 -*-
"""
@Time:2019/5/24 14:16
@Author: Cai jz
"""
from binascii import *
from crcmod import *
import time

# CRC16-MODBUS
def crc16Add(read):
    crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xFFFF, xorOut=0x0000)
    data = read.replace(" ", "")
    readcrcout = hex(crc16(unhexlify(data))).upper()
    str_list = list(readcrcout)
    print(str_list)
    if len(str_list) == 5:
        str_list.insert(2, '0')  # 位数不足补0
    crc_data = "".join(str_list)
    print(crc_data)
    read = read.strip() + ' ' + crc_data[4:] + ' ' + crc_data[2:4]
    print('CRC16校验:', crc_data[4:] + ' ' + crc_data[2:4])
    print('增加Modbus_CRC16校验:>>>', read)
    return read


if __name__ == '__main__':
    crc16Add("01 03 61 00 00 02")

你可能感兴趣的:(python学习)