简体   繁体   English

将Python 2字节校验和计算器转换为Python 3

[英]Translating Python 2 byte checksum calculator to Python 3

I'm trying to translate this Python 2 code to Python 3. 我正在尝试将此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

In Python 3 it causes a TypeError: 在Python 3中,它导致TypeError:

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

I have been trying to research the changes in strings and bytes but it is a bit overwhelming. 我一直在尝试研究字符串和字节的变化,但这有点让人不知所措。

The code basically translates individual characters in a bytestring to their integer equivalent; 该代码基本上将字节串中的各个字符转换为等效的整数。 the character \\x42 becomes 0x42 (or decimal 66), for example: 字符\\x42变为0x42(或十进制66),例如:

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

As an aside, you could do the same more simply with the ord() function : 顺便说一句,您可以使用ord()函数更简单地执行相同的操作:

>>> ord('\x42')
66

In Python 3, you already get integers when you iterate over a bytes object, which is why you get your error: 在Python 3中,当您遍历bytes对象时已经获得了整数,这就是为什么会出现错误的原因:

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

The whole struct.unpack() call can simply be dropped: 整个struct.unpack()调用可以简单地删除:

for char in packet:
    total += char

or simply use sum() to calculate the total in one step: 或简单地使用sum()一步计算总数:

total = sum(packet)

making the complete version: 制作完整版本:

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

Note that the Python 2 code could also use sum() , with the ord() function rather than use struct : total = sum(ord(c) for c in packed) . 请注意,Python 2代码还可以使用带有ord()函数的sum() ,而不是使用structtotal = sum(ord(c) for c in packed)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM