在python中计算crc8 dvb s2

时间:2018-10-25 19:46:39

标签: python c checksum

我需要在python中计算crc8 dvb s2校验和,但找不到有关此校验和如何真正工作的任何有用信息,因此我尝试转换此工作的C代码:

$order_array = array("order id: " . $order_id . ", order currency:" . $order_currency . ", order_version: " . $order_version );

在python代码中:

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;
    }

但是我似乎无法理解这是有问题的。 如果我给C函数提供字节'\ x00d \ x00 \ x00 \ x00',那么它给我的结果是'\ x8f'(是正确的),而Python函数给了我OverflowError:int太大,无法转换。 / p>

我的代码显然有问题,使数字越来越大,但我无法弄清楚到底是什么。

完整回溯:

import crc8
import operator 
def bxor(b1, b2): # use xor for bytes
    return bytes(map(operator.xor, b1, b2))
def blshift(b1, b2): # use shift left for bytes
    return (int.from_bytes( b1, byteorder='little') << int.from_bytes( b2, byteorder='little')).to_bytes(1, byteorder='little')
def _checksum(message): 
    #calculate crc
    crc = crc8.crc8()
    crc.update(message)
    crc_result = crc.digest()
    #calculate dvb
    crc_result = bxor(crc_result , message)
    for i in range(0, 7):
        if (crc_result == b'\x80') :
            crc_result = bxor((blshift(crc_result, b'\x01')) , b'\xD5')
        else:
            crc_result = blshift(crc_result, b'\x01')
    #-------------
    return crc_result;

1 个答案:

答案 0 :(得分:0)

int.to_bytes的文档中说:

  

如果整数不能用表示,则引发OverflowError   给定的字节数。

您使用的.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,而无需使用bxorblshift这样的辅助函数:

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