【问题标题】:Translating Python 2 byte checksum calculator to Python 3将 Python 2 字节校验和计算器转换为 Python 3
【发布时间】:2017-02-20 14:45:40
【问题描述】:

我正在尝试将此 Python 2 代码转换为 Python 3。

def calculate_checksum(packet):
  total = 0
  for char in packet:
    total += struct.unpack('B', char)[0]
  return (256 - (total % 256)) & 0xff

在 Python 3 中,它会导致 TypeError:

    total += struct.unpack('B', char)[0]
TypeError: a bytes-like object is required, not 'int'

我一直在尝试研究字符串和字节的变化,但是有点不知所措。

【问题讨论】:

  • 我会尝试bytes(char)。但minimal reproducible example 是最好的确认方式。
  • @Jean-FrançoisFabre:整个struct 通话是冗余的。它所做的只是将单个字符(无符号字符)转换为该字节的整数等效值。基本上是ord() 函数。除了在 Python 3 中,bytes 上的迭代已经给你提供了整数。
  • @MartijnPieters 当然!有时我忘记看大局

标签: python string python-2.7 python-3.x byte


【解决方案1】:

代码基本上将字节串中的单个字符转换为等效的整数;字符 \x42 变为 0x42(或十进制 66),例如:

>>> # Python 2
...
>>> struct.unpack('B', '\x42')[0]
66

顺便说一句,您可以更简单地使用ord() function

>>> ord('\x42')
66

在 Python 3 中,当您迭代 bytes 对象时,您已经获得整数,这就是您得到错误的原因:

>>> # Python 3
...
>>> b'\x42'[0]
66

整个struct.unpack() 电话都可以简单地挂断:

for char in packet:
    total += char

或者简单地使用sum()一步计算总数:

total = sum(packet)

制作完整版:

def calculate_checksum_ord(packet):
    total = sum(ord(c) for c in packet)
    return (256 - (total % 256)) & 0xff

请注意,Python 2 代码也可以使用sum()ord() 函数,而不是使用structtotal = sum(ord(c) for c in packed)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-18
    • 2020-06-25
    • 2021-04-05
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多