【发布时间】: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