Python字节到浮点转换

时间:2015-10-10 17:08:16

标签: python struct byte

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

longValue实际上表示在纪元中的时间,因为主要思想是将长纪元时间转换为字节。所以我遇到了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

有任何帮助吗?谢谢

1 个答案:

答案 0 :(得分:2)

使用相同的结构格式!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,)

here,而L用于4字节无符号长整数。这就是你得到错误的原因

struct.error: unpack requires a string argument of length 4
相关问题