我需要在python中计算crc8 dvb s2校验和,但是我找不到任何关于这个校验和是如何工作的有用信息,所以我试图转换这个工作的C代码:
uint8_t crc8_dvb_s2(uint8_t crc, unsigned char a)
{
crc ^= a;
for (int ii = 0; ii < 8; ++ii) {
if (crc & 0x80) {
crc = (crc << 1) ^ 0xD5;
} else {
crc = crc << 1;
}
}
return crc;
}
在python代码中:
^{pr2}$但它有一些问题,我似乎无法理解。 如果我给C函数指定字节'\x00d\x00\x00\x00',它的结果是'\x8f'(这是对的),而Python函数给我的是overflowerr:int太大,无法转换。在
很明显,我的代码出了问题,使得数字越来越大,但我不知道到底是什么。在
完整回溯:
---------------------------------------------------------------------------
OverflowError Traceback (most recent call last)
<ipython-input-226-8288eada1ce9> in <module>
----> 1 _checksum(b'\x00d\x00\x00\x00')
<ipython-input-225-2e5beaea293f> in _checksum(message)
18 crc_result = bxor((blshift(crc_result, b'\x01')) , b'\xD5')
19 else:
---> 20 crc_result = blshift(crc_result, b'\x01')
21 #-------------
22 return crc_result;
<ipython-input-225-2e5beaea293f> in blshift(b1, b2)
6 return bytes(map(operator.and_, b1, b2))
7 def blshift(b1, b2): # use shift left for bytes
----> 8 return (int.from_bytes( b1, byteorder='little') << int.from_bytes( b2, byteorder='little')).to_bytes(1, byteorder='little')
9 def _checksum(message):
10 #calculate crc
OverflowError: int too big to convert
^{} 的文档说明:
似乎使用
.to_bytes(1, byteorder='little')
的数字大于255(一个字节表示的最高数字)。在这个:
只有在
b2
介于0和255之间时才可以工作,而且我不明白将相同的值从整数转换为字节并返回的意义何在。在是否要计算
b2
的二进制表示的最低8位?那么您应该使用b2 % 256
。在您应该能够将这个C函数几乎按字面意思翻译成Python,而不需要像}这样的辅助函数:
bxor
或{相关问题 更多 >
编程相关推荐