【问题标题】:How to convert hex values to floating point number in python如何在python中将十六进制值转换为浮点数
【发布时间】:2020-07-01 07:15:00
【问题描述】:

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

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

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

谁能帮我解释为什么它在 python 中显示错误的值。谢谢

【问题讨论】:

    标签: python-3.x floating-point hex


    【解决方案1】:

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

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

    在 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
    

    【讨论】:

    • 您的解决方案给了我这个错误:AttributeError: 'str' object has no attribute 'decode'
    • 对不起,我的错。再检查一遍。
    • 对我来说它正在工作。它对你有用吗?如果有效,请将其标记为已解决,如果无效,请告诉我。
    • 谢谢你能看看这个问题吗stackoverflow.com/questions/60770615/…
    • 我已经在评论中回答了这个问题。 @SAndrew
    猜你喜欢
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 2010-12-08
    相关资源
    最近更新 更多