如何使用 ctypes 将字节转换为浮点数?

How to convert bytes to float using ctypes?

我想将 b'\xd8\x0fI@' 转换为 c_float。我正在寻找类似的东西:

>>> c_float(bytes=b'\xd8\x0fI@').value
3.1415

使用unpack from the struct

import ctypes, struct

ctypes.c_float(struct.unpack('<f', b'\xd8\x0fI@')[0]) # c_float(3.141592025756836)

使用联合:

import ctypes as ct

class Convert(ct.Union):
    _fields_ = (("my_bytes", ct.c_char * ct.sizeof(ct.c_float)),
                ("my_float", ct.c_float))

data_to_convert = b'\xd8\x0fI@'
conv = Convert()
conv.my_bytes = data_to_convert
print(conv.my_float)  # prints 3.141592025756836

您可能还想在进行转换之前检查长度。如果没有这样的检查,如果您尝试使用 long 字节序列,您将得到 ValueError,但如果您使用的字节序列太 [=],它不会提醒您17=]短。 (自动为您完成类型检查。)

if len(data_to_convert) != len(conv.my_bytes):
    raise ValueError