1

我有一个字节数组如下:

frame = bytearray()
frame.append(0x6)
frame.append(0x8)
frame.append(0xf1)
frame.append(0x1b)
frame.append(0x3)
frame.append(0x2)
frame.append(0x1)
frame.append(0x0)
frame.append(0x0)
frame.append(0x0)

我在帧的所有字节上应用 CRC:

seed = 0xB7D2
POLY = 0x8408


class CanCRC:
    def __init__(self, value=0):
        self.value = value

    def update(self, char: bytes, crcres):
        for b in range(8):
            if ((crcres & 0x0001) ^ (char & 0x0001) == 0x0001):
                crcres = crcres >> 1
                crcres ^= POLY
            else:
                crcres = crcres >> 1
            char = char >> 1
        return crcres

can = CanCRC(value=seed)
for i in range(0, len(frame)):
    can.value = can.update(frame[i], can.value)


frame.extend((can.value).to_bytes(2, byteorder='little'))

print(hex(can.value))
print(frame)

最终的 CRC 值为 0xcc30,但当添加到字节数组时,数组显示:

bytearray(b'\x06\x08\xf1\x1b\x03\x02\x01\x00\x00\x000\xcc')

为什么会这样?我得到\x000\xcc而不是\x30\xcc

我注意到数组中的其他字节也会发生这种情况..它没有正确编码或什么...

任何帮助表示赞赏

4

0 回答 0