Python双补码校验和

问题描述 投票:0回答:1

我在脚本中需要计算某个十六进制值的二补。

我从stackoverflow中获取了这个函数。

def checksum_calc(s):
    sum = 0
    for c in s:
        sum += ord(c)
    sum = -(sum % 256)
    return '%2X' % (sum & 0xFF)

但如果我引入数据,比如:

string = '\x00\x03\x03\xFF'

是正确的,但如果我像这样引入数据,

string = b'\x00\x03\x03\xFF'

我得到了错误的校验和。

你能帮我解决这个问题吗?

python python-3.x encode checksum
1个回答
0
投票

bytes 对象已经迭代到 int的,所以 ord 不工作。你的功能将适用于 bytes (但不是 str),去掉 ord() 调用 c 直接。

© www.soinside.com 2019 - 2024. All rights reserved.