How to convert byte array value to float In Python

Viewed 152

I have a list [142, 65, 110, 51] it needs to be converted to a float similar to c_float from ctypes lib. I don't know the logic for c_float.

I am trying to use module struct:

import struct

x = [142, 65, 110, 51]
ans = 0
for i, v in enumerate(x):
    ans += (v << (8 * i))

combined = ans  # 862863758

buf = struct.pack("d", combined)

fl = struct.unpack("ff", buf)
print(fl)

I get (-32768.0, 25.21441650390625), but I need a single float value.

In short I want something like [142, 65, 110, 51] => 0.0003232(some float value).

2 Answers

Use f rather than ff:

import struct

x = [142, 65, 110, 51]
fl = struct.unpack("f", bytes(x))
print(fl)

Which prints (5.54733148305786e-08,)

Note that you can skip your ans variable completely and directly convert x to a bytes object which can be unpacked.

import struct

x =  [142, 65, 110, 51]
ans = 0
for i, v in enumerate(x):
    ans += (v << (8 * i))

combined = ans  # 862863758

buf = struct.pack("I", combined)
fl = struct.unpack("f", buf)
print(fl[0])  #  --> 5.54733148305786e-08
Related