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

时间:2018-07-24 16:01:42

标签: python bit-manipulation crc

这是我第一次在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:]

我不知道正确的Python方式:

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

CRC = MSG[-24:]

如何用Pythonic方式正确地做到这一点?

2 个答案:

答案 0 :(得分:1)

如果可以使用库,建议您搜索自己喜欢的bitstring / bitvector库。例如,使用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))

答案 1 :(得分:0)

尽管它放弃了直接位算法,但是您可以采用一种更加Python化的方法。

msg_hex = "8D4840D6202CC371C32CE0576098"
msg_dec = int(msg_hex, 16)
msg_bin = list(bin(msg_dec)[2:].zfill(8))

generator = "1111111111111010000001001"

for i in range(88):
    if msg_bin[i] == "1":
        msg_bin[i:i+24] = ["1" if a != b else "0" for a, b in zip(msg_bin[i:i+24], generator)]

if int("".join(msg_bin[-24:])):
    print("corrupted")

如果需要,可以将"1" if a != b else "0"替换为"01"[a!=b],但我认为前者更具Python特色。

我无法验证此解决方案是否正确,因为您的代码无法编译,也没有提及给定的生成器和消息应产生的内容。我确实怀疑问题陈述中存在错误,因为它正在检查最后24位,但是生成器包含25位。