__author__ = 'Administrator'
from binascii import unhexlify
DI = 0x07 crc8_table = []
#Should be called before any other crc function def init_crc8(): for i in range(256): crc = i for j in range(8): tmp = crc & 0x80 if tmp: crc = (crc << 1)^DI else: crc = (crc << 1)^0 crc8_table.append(crc & 0xFF) #for k in crc8_table: # print(k)
# For a byte array whose accumulated crc value is stored in *crc, computes # resultant crc obtained by appending m to the byte array def crc8(buf, n): crc_r = 0 if not(len(crc8_table)): init_crc8()
for i in range(n): crc_r = crc8_table[crc_r ^ buf[i]] crc_r &= 0xFF crc = hex(~crc_r & 0xff) return crc
#測試crc8程序 def TestCrc8(): data = "A5 D1 08 01 00 04 08 03 01 23 23 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00" data = data.replace(" ","") SendData = unhexlify(bytes(data,"UTF-8")) crc = crc8(SendData, len(SendData)) data += crc[2:] + "5A" SendData = unhexlify(bytes(data,"UTF-8")) print(SendData)
if __name__ == "__main__": TestCrc8()
|