[英]Python byte to float conversion
from struct import *
longValue = 1447460000
print struct.pack('!q',longValue)
The longValue is actually signifies time in epoch as the main idea is to convert the epoch time which is a long, into bytes. longValue 实际上表示纪元中的时间,因为主要思想是将很长的纪元时间转换为字节。 So I came across struct module and this seems quite helpful too.所以我遇到了 struct 模块,这似乎也很有帮助。
The output that I get is:-我得到的输出是:-
'\x00\x00\x00\x00VF|\xa0'
Now, I want to make sure that this result is correct, so I want to convert these bytes back to the long.现在,我想确保这个结果是正确的,所以我想将这些字节转换回 long。
This is what I am trying:-这就是我正在尝试的:-
struct.unpack("<L", "\x00\x00\x00\x00VF|\xa0")
But this gives me error:-但这给了我错误:-
struct.error: unpack requires a string argument of length 4
Any help?Thanks有什么帮助吗?谢谢
Use the same struct format, !q
, to unpack as you did to pack:使用与打包时相同的结构格式!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 , while L
is for 4-byte unsigned longs. q
用于 8 字节长整数,而L
用于 4 字节无符号长整数。 That is why you got the error这就是为什么你得到错误
struct.error: unpack requires a string argument of length 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.