2

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).

4
  • 1
    "but i need a single float value" - which one in this case ? Commented Jan 21, 2021 at 11:56
  • @frederic single value means [142, 65, 110, 51] => 0.0003232 something like that. Commented Jan 21, 2021 at 11:58
  • There are numerous functions which will map 4 bytes to a float. Are you looking for a specific float (e.g. the one in which those bytes are its underlying representation as an IEEE single-precision float)? "something like" is too vague to work with. Commented Jan 21, 2021 at 12:06
  • @JohnColeman I am looking for similar technique as c_float from ctypes python lib. Commented Jan 21, 2021 at 12:10

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.