Skip to main content
 首页 » 编程设计

python之如何在 Python 中对原始二进制数据使用按位运算符进行 CRC 检查

2024年12月31日12zengkefu

这是我第一次在 Python 中使用二进制运算符和原始二进制数据,并且我正在努力编写文档中定义的 CRC 检查代码。

文档在如下伪代码中定义了 CRC 校验:

GENERATOR = 1111111111111010000001001 
 
MSG = binary("8D4840D6202CC371C32CE0576098")  # total 112 bits 
 
FOR i FROM 0 TO 88:                           # 112 - 24 parity bits 
  if MSG[i] is 1: 
    MSG[i:i+24] = MSG[i:i+24] ^ GENERATOR 
 
CRC = MSG[-24:]                               # last 24 bits 
 
IF CRC not 0: 
  MSG is corrupted 

到目前为止,我已经编写了以下代码:

adsb_hex = "8D4840D6202CC371C32CE0576098" 
adsb_dec = int(adsb_hex, 16) 
adsb_bin = bin(adsb_dec)[2:].zfill(8) 
 
generator = 0b1111111111111010000001001 
 
adsb_bin_list = [int((adsb_dec >> bit) & 1) for bit in range(112 - 1, -1, -1)] 
 
check = [] 
for i in range(88): 
    curr_bit = adsb_bin_list[i] 
    if curr_bit is 1: 
        check[i:i+24] = int(adsb_bin_list[i:i+24]) ^ generator 
 
crc = check[-24:] 

我不知道正确的 Pythonic 方法:

MSG[i:i+24] = MSG[i:i+24] ^ GENERATOR 
 
CRC = MSG[-24:] 

我怎样才能以 Pythonic 的方式正确地做到这一点?

请您参考如下方法:

如果您可以使用库,我建议您搜索您最喜欢的位串/位向量库。例如,使用 BitVector==3.4.8你可以写

from BitVector import BitVector 
 
generator = BitVector(bitstring='1111111111111010000001001') 
crc_length = len(generator) - 1 
 
def compute_crc(message : BitVector) -> BitVector: 
    content_length = len(message) - crc_length 
    # to encode a message, you pad it with 0 
    # to decode, you pass in the message with the crc appended 
    assert content_length >= 0 
    # operate on a copy of the data 
    message = message.deep_copy() 
    for i in range(content_length): 
        if message[i]: 
            message[i:i + len(generator)] ^= generator 
    return message[-crc_length:] 
 
if __name__ == "__main__": 
    adsb_hex = "8D4840D6202CC371C32CE0576098" 
    adsb_crc = compute_crc(BitVector(hexstring = adsb_hex))