求助,关于python的一段代码
用python语言 如何将test1.txt中一串数字进行crc校验存入test2.txt中,其中
test1.txt 中数字为0B 01 00 00 00 0A 13 08 21 13 56 17
test2.txt 中数字为0B 01 00 00 00 0A 13 08 21 13 56 17 7E 7F python 语言 crc校验
[解决办法]
字符串变成byte串可以用binascii模块。python标准库中只有支持crc32的模块,有一个第三方软件包叫crc16(https://pypi.python.org/pypi/crc16/0.1.0)可以用。安装了crc16后:
In [24]: import binascii, crc16
In [25]: def crc(s):
...: s_bin = binascii.unhexlify(s)
...: return hex(crc16.crc16xmodem(s_bin))
In [26]: s = "0B 01 00 00 00 0A 13 08 21 13 56 17"
In [27]: crc(s.replace(' ', '')) # 先要去掉空格
Out[27]: '0x7e7f'
# -*-coding: UTF-8 -*-
from binascii import crc32
from ctypes import c_uint
def zCrc32(_path):
try:
crc = 0
blocksize = 1 << 16 # 1024 * 64
with open(_path, "rb") as f:
block = f.read(blocksize)
while 1:
if block == b'':
break
crc = crc32(block, crc)
block = f.read(blocksize)
return '{:008X}'.format(c_uint(crc).value)
except:
return ''