将struct.unpack从python 2.7移植到3

时间:2015-11-27 13:58:12

标签: python

以下代码在python 2.7中运行良好:

def GetMaxNoise(data, max_noise):
    for byte in data:
        noise = ComputeNoise(struct.unpack('=B',byte)[0])
        if max_noise < noise:
            max_noise = noise
    return max_noise

其中data是一个包含二进制数据的字符串(取自网络数据包)。

我试图将它移植到Python 3,我得到了这个:

  

文件&#34; Desktop / Test.py&#34;,第2374行,GetMaxNoise

     

noise = ComputeNoise(struct.unpack(&#39; = B&#39;,byte)[0])

     

TypeError:&#39; int&#39;不支持缓冲区接口

如何转换&#34;数据&#34;到unpack()所需的适当类型?

2 个答案:

答案 0 :(得分:3)

假设data变量是从网络数据包上的二进制文件获得的字节字符串,它在Python2和Python3中的处理方式不同。

在Python2中,它是一个字符串。当您迭代其值时,您将获得单字节字符串,并使用struct.unpack('=B')[0]

转换为int

在Python3中,它是一个bytes对象。当你迭代它的值时,你直接获得整数!所以你应该直接使用:

def GetMaxNoise(data, max_noise):
    for byte in data:
        noise = ComputeNoise(byte)  # byte is already the int value of the byte...
        if max_noise < noise:
            max_noise = noise
    return max_noise

答案 1 :(得分:1)

从struct module https://docs.python.org/3.4/library/struct.html的文档中我看到unpack方法期望它是实现缓冲协议的第二个参数,因此它通常需要bytes

您的data对象似乎属于bytes类型,因为它是从某处读取的。当您使用for循环对其进行迭代时,最终会将byte变量设为单int个值。

我不知道您的代码应该做什么以及如何做,但可能会改变您对data对象进行迭代以处理int而不是bytes {的方式{1}}?

length == 1
相关问题