python-3.x - 如何在Python中将十六进制值转换为 float

标签 python-3.x floating-point hex

我有十六进制值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/

相关文章:

python - 仅位置参数与 python 3.7 的兼容性

python - 如何使用 openCV python 更改现有视频的帧速率 FPS

python - 面对python继承中的问题

java - 浮点舍入(在 Java 中)

写入内存时,从 Float 到 Hex 的 C++ 转换不正确

c# - LINQ to XML .Count() 方法返回 HEX?如何将其转换为 Int?

python - 将整数或整数列表转换为集合

python - 为什么整数除法和除法后转换为 int 的结果对于大数不同?

c++ - 启用浮点异常的浮点堆栈处理

c++ - 弄清楚网络、十六进制和 ascii 如何交互