简体   繁体   中英

How to convert byte array value to float In Python

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM