Porting struct.unpack from python 2.7 to 3

后端 未结 2 917
抹茶落季
抹茶落季 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:51

    Assuming the data variable is a string of bytes that you got from a binary file on a network packet, it it not processed the same in Python2 and Python3.

    In Python2, it is a string. When you iterate its values, you get single byte strings, that you convert to int with struct.unpack('=B')[0]

    In Python3, it is a bytes object. When you iterate its values, you directly get integers! So you should directly use:

    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
    

提交回复
热议问题