Porting struct.unpack from python 2.7 to 3

后端 未结 2 890
抹茶落季
抹茶落季 2021-01-18 11:17

The following code works fine in python 2.7:

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


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-18 11:52

    From the docs of the struct module https://docs.python.org/3.4/library/struct.html I see that the unpack method expects it's second argument to implement Buffer Protocol, so it generally expects bytes.

    Your data object seems to be of the type bytes as it's read from somewhere. When you iterate over it with the for loop, you end up with byte variable being single int values.

    I don't know what your code is supposed to do and how, but maybe change the way you iterate over your data object to handle not ints but bytes of length == 1?

    for i in range(len(data)):
        byte = data[i:i+1]
        print(byte)
    

提交回复
热议问题