user974168
user974168

Reputation: 237

Converting python list to float

I have library function which reads from hardware and returns

value = readregister(registerindex,numbytes)

where value is a python list.

If numbytes is 4, then the complete returned number will be returned in

value[0],value[1],value[2] and value[3]   

The actual value in the register was a floating point number. So how do I convert this list value of 4 elements to a python floating point number ?

Upvotes: 3

Views: 2298

Answers (2)

mtrw
mtrw

Reputation: 35088

You need to first convert your list of four bytes to a Python string of bytes, then convert the string into a floating point value.

Say you have the list value = [0, 0, 192, 63]. First convert into a string of bytes:

vstr = ''.join([chr(k) for k in slist]) #chr converts the integer into the corresponding byte

Then, as dyoo points out you can use struct.unpack to convert the string of bytes to a floating point number:

f = struct.unpack("f", vstr)

In this example f is 1.5.

One thing you need to be aware of is the endianness of your hardware device. If the endianness is reversed from the platform you do the unpack on, using "f" for the format string to struct.unpack will give the wrong answer. Prepend the format string with < for little-endian devices, and > for big-endian devices:

fle = struct.unpack("<f", ''.join([chr(k) for k in value]) #for little-endian HW
fbe = struct.unpack(">f", ''.join([chr(k) for k in value]) #for big-endian HW

Upvotes: 5

dyoo
dyoo

Reputation: 12003

You are probably looking for struct.unpack.

Upvotes: 1

Related Questions