Python 字节到浮点数的转换

Python byte to float conversion

from struct import *
longValue = 1447460000
print struct.pack('!q',longValue)

longValue实际上是表示epoch的时间,主要思想是将一个long的epoch时间转换成字节。所以我遇到了 struct module ,这似乎也很有帮助。

我得到的输出是:-

'\x00\x00\x00\x00VF|\xa0'

现在,我想确保这个结果是正确的,所以我想将这些字节转换回 long。

这就是我正在尝试的:-

struct.unpack("<L", "\x00\x00\x00\x00VF|\xa0")

但这给了我错误:-

struct.error: unpack requires a string argument of length 4

有什么帮助吗?谢谢

使用相同的结构格式,!q,像打包一样解包:

In [6]: import struct

In [7]: longValue = 1447460000

In [8]: struct.pack('!q',longValue)
Out[8]: '\x00\x00\x00\x00VF|\xa0'

In [9]: struct.unpack('!q', struct.pack('!q',longValue))
Out[9]: (1447460000,)

q is for 8-byte long ints,而 L 用于 4 字节无符号长整数。这就是您收到错误

的原因
struct.error: unpack requires a string argument of length 4