问题
我正在为一个嵌入式设备编写代码。许多用于CRC-CCITT 16位计算的解决方案都需要库。
考虑到使用库几乎是不可能的,而且会消耗库的资源,因此需要一个函数。
可能的解决方案
以下CRC计算在网上找到。但是,它的实现是不正确的。
http://bytes.com/topic/python/insights/887357-python-check-crc-frame-crc-16-ccitt
def checkCRC(message):
#CRC-16-CITT poly, the CRC sheme used by ymodem protocol
poly = 0x11021
#16bit operation register, initialized to zeros
reg = 0xFFFF
#pad the end of the message with the size of the poly
message += '\x00\x00'
#for each bit in the message
for byte in message:
mask = 0x80
while(mask > 0):
#left shift by one
reg<<=1
#input the next bit from the message into the right hand side of the op reg
if ord(byte) & mask:
reg += 1
mask>>=1
#if a one popped out the left of the reg, xor reg w/poly
if reg > 0xffff:
#eliminate any one that popped out the left
reg &= 0xffff
#xor with the poly, this is the remainder
reg ^= poly
return reg
现有的在线解决方案
以下链接正确计算16位CRC。
http://www.lammertbies.nl/comm/info/crc-calculation.html#intr
“CRC-CCITT(XModem)”下的结果是正确的CRC。
规格
我相信现有在线解决方案中的“CRC-CCITT(XModem)”计算使用了0x1021
多项式。
问题
如果有人可以编写一个新函数,或者提供方向来按照所需的规范解决checkCRC
函数。请注意,使用库或任何import
都没有帮助。
原始函数
checkCRC
也可以执行“CRC-CCITT(XModem)”。刚刚设置:
而不是
这是C库的一个python端口,来自CRC-CCITT XMODEM的http://www.lammertbies.nl/comm/info/crc-calculation.html
这个库对于实际的用例很有趣,因为它预先计算crc表以提高速度。
用法(带字符串或字节列表):
测试给出:
'0x31c3'
如果在开始时用
poly = 0x1021
替换poly = 0x11021
,则建议的checkCRC
例程是CRC-CCITT变体“1D0F”。下面是一个可以转换为Python的C版本:
crc
初始化为零。相关问题 更多 >
编程相关推荐