对 python 字节类型执行校验和计算

Performing checksum calculation on python bytes type

我第一次需要处理原始数据(具有不同的字节顺序、2 的补码……),因此终于弄清楚了如何使用字节类型。 我需要实现以下校验和算法。我了解 C 代码,但想知道如何在 Python3 中优雅地执行此操作... 我确定我可以想出一些可行的方法,但效率低下或不可靠

The checksum algorithm used is the 8-bit Fletcher algorithm. This algorithm works as follows:

  • Buffer[N] is an array of bytes that contains the data over which the checksum is to be calculated.
  • The two CK_A and CK_A values are 8-bit unsigned integers, only! If implementing with larger- sized integer values, make sure to mask both CK_A and CK_B with the value 0xff after both operations in the loop.
  • After the loop, the two U1 values contain the checksum, transmitted after the message payload, which concludes the frame.
CK_A = 0, CK_B = 0 For (I = 0; I < N; I++)
    {
    CK_A = CK_A + Buffer[I]
    CK_B = CK_B + CK_A
    } ```

我的数据结构如下:

source = b'\xb5b\x01<@\x00\x01\x00\x00\x00hUX\x17\xdd\xff\xff\xff^\xff\xff\xff\xff\xff\xff\xff\xa6\x00\x00\x00F\xee\x88\x01\x00\x00\x00\x00\xa5\xf5\xd1\x05d\x00\x00\x00d\x00\x00\x00j\x00\x00\x00d\x00\x00\x00\xcb\x86\x00\x00\x00\x00\x00\x007\x01\x00\x00\xcd\xa2'

我想出了几个关于如何做到这一点的想法,但有问题。 以下是我现在的位置,我已经添加了关于我认为它会如何工作(但没有)的评论。

for b in source[5:-2]:

    # The following results in "TypeError("can't concat int to bytes")"
    # So I take one element of a byte, then I would expect to get a single byte.
    # However, I get an int.
    # Should I convert the left part of the operation to an int first?
    # I suppose I could get this done in a couple of steps but it seems this can't be the "correct" way...

    CK_A[-1:] += b

    # I hoped the following would work as a bitmask, 
    # (by keeping only the last byte) thus "emulating" an uint8_t
    # Might not be the correct/best assumption...

    CK_A = CK_A[-1:] 
    CK_B[-1:] += CK_A
    CK_B = CK_B[-1:]
ret = CK_A + CK_B

显然,我没有完全理解这种字节类型 works/should 是如何使用的。

看来我把事情搞得太难了...

    CK_A = 0
    CK_B = 0

    for b in source:
        CK_A += b
        CK_B += CK_A

    CK_A %= 0x100
    CK_B %= 0x100
        
    ret = bytes()
    ret = int.to_bytes(CK_A,1, 'big') + int.to_bytes(CK_B,1,'big')

%=0x100 用作位掩码,仅保留 8 LSB...