nowox
nowox

Reputation: 29116

How to convert bytes to float using ctypes?

I would like to convert b'\xd8\x0fI@' into a c_float. I am looking for something like:

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

Upvotes: 1

Views: 678

Answers (2)

alani
alani

Reputation: 13079

Use a union:

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

You would probably also want to check the length before doing the conversion. Without such a check you will get a ValueError if you try to use too long a sequence of bytes, but it will not alert you if you use one that is too short. (The type checking is done for you automatically.)

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

Upvotes: 2

FluidLight
FluidLight

Reputation: 471

Use unpack from the struct library

import ctypes, struct

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

Upvotes: 0

Related Questions