16进制浮点数相互转换

来源:互联网 发布:迪姆软件 编辑:程序博客网 时间:2024/06/11 20:06

# -*- coding: utf8 -*-
import ctypes
def h2f(s):
    cp = ctypes.pointer(ctypes.c_long(s))
    fp = ctypes.cast(cp, ctypes.POINTER(ctypes.c_float))
    return fp.contents.value
def f2h(s):
    fp = ctypes.pointer(ctypes.c_float(s))
    cp = ctypes.cast(fp, ctypes.POINTER(ctypes.c_long))
    return hex(cp.contents.value)
print(f2h(3.1415))
print(h2f(0x40490e56))


#-------------------

ret = f2h(3.1415)       # ret  = "0x40490e56"
ret2 = h2f(int(ret,16)) # ret2 = 3.14149999619
ret3 = "%.4f"%ret2      # ret3 = "3.1415"
ret4 = float(ret3)      # ret4 = 3.1415

原创粉丝点击