16进制浮点数相互转换

论坛 期权论坛 脚本     
匿名技术用户   2020-12-22 19:32   11   0

# -*- 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

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP