用python计算crc8 dvb s2

2024-10-01 02:39:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在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

Tags: 代码ininputreturnbytesipythonresultb2
1条回答
网友
1楼 · 发布于 2024-10-01 02:39:36

^{}的文档说明:

An OverflowError is raised if the integer is not representable with the given number of bytes.

似乎使用.to_bytes(1, byteorder='little')的数字大于255(一个字节表示的最高数字)。在

这个:

int.from_bytes( b2, byteorder='little')).to_bytes(1, byteorder='little')

只有在b2介于0和255之间时才可以工作,而且我不明白将相同的值从整数转换为字节并返回的意义何在。在

是否要计算b2的二进制表示的最低8位?那么您应该使用b2 % 256。在


您应该能够将这个C函数几乎按字面意思翻译成Python,而不需要像bxor或{}这样的辅助函数:

def crc8_dvb_s2(crc, a):
    crc ^= a
    for _ in range(8):
        if crc & 0x80:
            crc = ((crc << 1) ^ 0xD5) % 256
        else:
            crc = (crc << 1) % 256
    return crc

相关问题 更多 >