指向十六进制的浮点指针

2024-10-03 11:15:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我用来转换hexadecimals > float pointers的代码:

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

但我不确定如何才能扭转这种影响。在

我试图从float pointer > hexadecimal开始,而不是hexadecimal > float pointer。在


Tags: thetofromconvertfloatcpreturnsint
2条回答

您可以使用struct将十六进制转换为浮点

import struct

struct.unpack('!f', '41995C29'.decode('hex'))[0]

将提供:

^{pr2}$

你也做同样的事,但是向后:

  1. 把浮点数转换成整数
  2. 把整数转换成十六进制

代码:

def float_to_hex(x):
    fp = pointer(c_float(x))
    ip = cast(fp, POINTER(c_int))
    x = ip.contents.value
    return '{:02X}'.format(x)

输出:

^{pr2}$

相关问题 更多 >