我有十六进制值4396 eccd
。如果我使用一些 online calculator 将其转换为 float ,我得到的值为 301.85
这是正确的。
但是当我使用 python 转换它时,我得到了一些不同的值:
>>> float.fromhex('0x4396eccd')
1133964493.0
任何人都可以帮我解释为什么它在 python 中显示错误的值。谢谢
最佳答案
要了解 fromhex()
的作用,您可以引用:https://python-reference.readthedocs.io/en/latest/docs/float/fromhex.html
您最好使用 struct
模块,而不是使用 fromhex()
将十六进制字符串转换为 float 。
在 python 2.x 中
>>> import struct
>>> struct.unpack('!f', '41973333'.decode('hex'))[0]
18.899999618530273
在 python 3.x 中使用:
bytes.fromhex('41973333')
而不是 '41973333'.decode('hex')
所以会是这样的:
>>> import struct
>>> struct.unpack('!f', bytes.fromhex('41973333'))[0]
18.899999618530273
关于python-3.x - 如何在Python中将十六进制值转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60769273/