将十六进制转换为浮点

发布于 2021-01-29 19:34:22

如何在Python中将以下十六进制字符串转换为float(单精度32位)?

"41973333" -> 1.88999996185302734375E1

"41995C29" -> 1.91700000762939453125E1

"470FC614" -> 3.6806078125E4
关注者
0
被浏览
84
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    Python 3中

    >>> import struct
    >>> struct.unpack('!f', bytes.fromhex('41973333'))[0]
    18.899999618530273
    >>> struct.unpack('!f', bytes.fromhex('41995C29'))[0]
    19.170000076293945
    >>> struct.unpack('!f', bytes.fromhex('470FC614'))[0]
    36806.078125
    

    Python 2中

    >>> import struct
    >>> struct.unpack('!f', '41973333'.decode('hex'))[0]
    18.899999618530273
    >>> struct.unpack('!f', '41995C29'.decode('hex'))[0]
    19.170000076293945
    >>> struct.unpack('!f', '470FC614'.decode('hex'))[0]
    36806.078125
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看