检查 python 中字节校验和的最佳方法

Best way to check checksum of bytes in python

我从串行端口接收到一些数据包。数据包示例:

                         last 2 bytes
                              /\
[ data length ] [ data ] [packet crc]

我得到crc,例如b'w\x06'。值为 125 (sum(b'w\x06') = 125)。我计算数据包的crc:sum(data)。我得到 1655。我知道 1655b'w' 相同,但我不知道如何将它简单地转换为 125 并与正确的校验和进行比较。我需要将 1655 转换为与接收到的数据包字节相同的值(125b'w\x06')? binascii/struct/其他?

谢谢

您可以使用 int.from_bytes:

int.from_bytes(b'w\x06', 'little')

struct:

struct.unpack("<H", b'w\x06')[0]