在 python 中打包和解包浮点值

Packing and unpacking float values in python

为什么当我尝试打包 float 对象时 python return "odd values"?例如:

>>> import struct,time

>>> struct.pack('d', time.time())
b'\xe0LC|\xf6l\xd7A'

>>> struct.unpack('d', b'\xe0LC|\xf6l\xd7A')
(1572067825.051567,)

为什么它将值解包为元组而不是浮点数?然后,为什么它使用 LC|l 之类的值——我认为它会以十六进制形式打包项目?

unpack 的文档明确指出结果是一个元组:

Unpack from the buffer buffer (presumably packed by pack(format, ...)) according to the format string format. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes must match the size required by the format, as reflected by calcsize().

您可以通过以下方式查看所有可能字节的表示:

for i in range(256):
    print("{} : {}".format(i, bytes([i])))

例如124表示为b'|'。在你的例子中,b'\xe0LC|\xf6l\xd7A'bytes([224, 76, 67, 124, 246, 108, 215, 65]) 的表示。