结构解包我只在 python 2 中工作,我需要了解如何在 Python 3 中做到这一点



我正在尝试在python 3中运行此代码,它仅适用于python 2

struct.unpack('f', "".join(map(chr, bytes)))[0]
def get_float(data, index):
    bytes = data[4*index:(index+1)*4]
    return struct.unpack('f', "".join(map(chr, bytes)))[0]

我收到此错误

类型错误:需要类似字节的对象,而不是"str"

您可以尝试以下操作:

struct.unpack('f', b"".join(map(chr, bytes)))[0]

b" 是一个字节字符串。由于解包需要字节,因此需要使用字节字符串连接方法。

编辑:您不需要将字节映射到字符。您可以使用:

struct.unpack('f', bytes)[0]

请注意,字节隐藏了类字节。

最新更新