等同于Python 2 str.decode('hex')的Python 3

时间:2018-11-19 15:03:56

标签: python python-3.x python-2.7 decode

我正在尝试将十六进制的IEEE 754浮点数转换为标准python浮点数。

以下内容在Python 2.x中有效:

foo ='4074145c00000005'
conv_pound = struct.unpack('!d', foo.decode('hex'))[0]
print(conv_pound)

并产生以下输出(确实是我想要的数字):

321.272460938

但是,python 3没有str.decode方法,我正在努力寻找方法。有提示吗?

1 个答案:

答案 0 :(得分:7)

bytes.fromhex()在python3中为我工作:

Python 3.6.6 (default, Sep 12 2018, 18:26:19) 
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> foo ='4074145c00000005'
>>> import struct
>>> struct.unpack('!d', bytes.fromhex(foo))
(321.2724609375003,)
>>> struct.unpack('!d', bytes.fromhex(foo))[0]
321.2724609375003