如何将十六进制值转换为 python 中的浮点数

How to convert hex values to floating point number in python

我有十六进制值 4396 eccd。如果我使用一些 online calculator 将其转换为浮点数,我得到的值是 301.85,这是正确的。

但是当我使用 python 转换它时,我得到了一些不同的值:

>>> float.fromhex('0x4396eccd')
1133964493.0

任何人都可以帮助我解释为什么它在 python 中显示错误的值。谢谢

要了解fromhex()的作用,您可以参考:https://python-reference.readthedocs.io/en/latest/docs/float/fromhex.html

不要使用 fromhex() 十六进制字符串到浮点数,你最好使用 struct 模块。

在python2.x

>>> import struct
>>> struct.unpack('!f', '41973333'.decode('hex'))[0]
18.899999618530273

在python3.x中使用:

bytes.fromhex('41973333') 而不是 '41973333'.decode('hex')

所以会变成这样:

>>> import struct
>>> struct.unpack('!f', bytes.fromhex('41973333'))[0]
18.899999618530273