我一直在试图理解CRC32计算,但没有取得太大的进展,我似乎得到的值与应该得到的值不匹配。
我知道Python有能够生成这些校验和的库(即zlib和binascii),但我不能使用它们,因为MicroPython上不存在CRC功能。
到目前为止,我有以下代码:
import binascii
import zlib
from array import array
poly = 0xEDB88320
table = array('L')
for byte in range(256):
crc = 0
for bit in range(8):
if (byte ^ crc) & 1:
crc = (crc >> 1) ^ poly
else:
crc >>= 1
byte >>= 1
table.append(crc)
def crc32(string):
value = 0xffffffffL
for ch in string:
value = table[(ord(ch) ^ value) & 0x000000ffL] ^ (value >> 8)
return value
teststring = "test"
print "binascii calc: 0x%08x" % (binascii.crc32(teststring) & 0xffffffff)
print "zlib calc: 0x%08x" % (zlib.crc32(teststring) & 0xffffffff)
print "my calc: 0x%08x" % (crc32(teststring))
然后我得到了以下输出:
binascii calc: 0xd87f7e0c
zlib calc: 0xd87f7e0c
my calc: 0x2780810c
binascii和zlib的计算结果是一致的,但我的计算结果不同。我认为所计算的字节表是正确的,因为我已经与网上可用的示例进行了比较。因此问题必须在计算每个字节的程序中,有没有人能指点我正确的方向?
提前感谢!
'\xff\xff\xff\xff'
时它返回ffffffff
,这是一个好兆头。 :) - PM 2Ringreturn ~value & 0xffffffff
。这两个都比return (-1 - value) & 0xffffffff
更简洁。你的版本可能是最好的,因为它使用了最少的操作。 - PM 2Ring