在Python ctypes uint32字段中插入IEEE浮点的字节表示的干净方法?

2024-05-29 08:21:16 发布

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

我正在使用一个外部提供的ctypes结构,它有一些字段定义为通用的catch all字段。data字段的类型基于mode字段的,如本例所示:

CONTAINS_ONE_FLOAT = 1

class TestStruct(ctypes.Structure):
    pass

TestStruct._fields_ = [
    ('mode', ctypes.c_uint32),
    ('data', ctypes.c_uint32 * 2)
]

每当mode设置为CONTAINS_ONE_FLOAT时,我需要在data中存储一个单精度(32位)浮点值。data的第二个字不在此模式中使用。你知道吗

到目前为止,我只能使用ctypes转换来找出这种方法。这似乎太冗长了,但它的工作。你知道吗

float_value = 42.42
float_value_c = ctypes.c_float(float_value)
float_value_cp = ctypes.POINTER(ctypes.c_float)(float_value_c)
int_val_p = ctypes.cast(float_value_cp, ctypes.POINTER(ctypes.c_uint32))
int_val = int_val_p.contents

x = TestStruct()
x.mode = CONTAINS_ONE_FLOAT
x.data[0] = int_val

print("Should be 1110027796: " + str(x.data[0]))

有没有更好的方法不需要5个步骤?你知道吗


Tags: 方法datavaluemodevalfloatctypesone
2条回答

您描述的模式通常在C中用union实现;您可以对ctypes执行相同的操作:

CONTAINS_ONE_FLOAT = 1

class TestStructData(ctypes.Union):
    _fields_ = [
        ('one_float', ctypes.c_float), 
        ('two_dword', ctypes.c_uint32 * 2)
    ] 

class TestStruct(ctypes.Structure):
    _fields_ = [
        ('mode', ctypes.c_uint32),
        ('data', TestStructData)
    ]

要读/写浮点数(或任何其他类型的浮点数),请读/写TestStructData的相应字段。你知道吗

您可以使用^{}

float_bytes = struct.pack('=f', float_value)
x.data[0] = struct.unpack('=I', float_bytes)[0]

相关问题 更多 >

    热门问题