发布时间:2019-09-15 10:08:40编辑:auto阅读(4494)
<pre name="code" class="python"><span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">参考网址http://blog.163.com/du_minchao@126/blog/static/107495394201075114028606/</span>
上边参考网址内的计算方法亲自算一遍就知道CRC怎么使用了(就是上边的图片),搜索了一下,大部分都是C语言实现,工作期间需要用Python实现求字符串CRC校验的函数,使用查表法实现
#!/usr/bin/env python
# -*- coding: utf-8 -*-
POLYNOMIAL = 0x1021
INITIAL_REMAINDER = 0xFFFF
FINAL_XOR_VALUE = 0x0000
WIDTH = 16
TOPBIT = (1 << (WIDTH - 1))
crcTable = {}
def crcInit():
SHIFT = WIDTH - 8
for step in range(0, 256):
remainder = step << SHIFT
for bit in range(8, 0, -1):
if remainder & TOPBIT:
remainder = ((remainder << 1) & 0xFFFF) ^ 0x1021
else:
remainder = remainder << 1
crcTable[step] = remainder
def crcFast(message, nBytes):
crcInit()
remainder = 0xFFFF
data = 0
byte = 0
while byte < nBytes:
data = ord(message[byte]) ^ (remainder >> (WIDTH - 8))
remainder = crcTable[data] ^ ((remainder << 8)&0xFFFF)
byte = byte + 1
return hex(remainder)[2: ]
上一篇: python学习笔记3:转义字符
下一篇: 【Python】Ceph的python接
47842
46390
37283
34733
29313
25973
24916
19951
19545
18030
5792°
6413°
5927°
5961°
7064°
5911°
5944°
6438°
6404°
7778°