【转】Python 十六进制与浮点数互相转换

在python中虽然很少用到十六进制或者二进制数据,但是当要处理这些数据时,
进制的转换还是必要的,这里把找到的浮点数转换为十六进制,十六进制转换为浮点数
的方法分享出来。有了十六进制数据,二进制也好,十进制,八进制也好,都很方便转换了。

1. 浮点数转为十六进制数据

>>> struct.pack("<f", 238.3).encode('hex')
'cd4c6e43'

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

或者

from ctypes import *

def convert(s):
    i = int(s, 16)                   # convert from hex to a Python int
    cp = pointer(c_int(i))           # make this into a c integer
    fp = cast(cp, POINTER(c_float))  # cast the int pointer to a float pointer
    return fp.contents.value         # dereference the pointer, get the float

print convert("41973333")    # returns 1.88999996185302734375E1

print convert("41995C29")    # returns 1.91700000762939453125E1

print convert("470FC614")    # returns 3.6806078125E4

转自:http://stackoverflow.com/questions/1592158/convert-hex-to-float?answertab=votes#tab-top
 
     http://stackoverflow.com/questions/10981661/float-number-to-inverse-order-hex?answertab=votes#tab-top

发表评论

邮箱地址不会被公开。 必填项已用*标注

机器人检查 *

分享我的最新文章标题到这里

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据