3

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 ?

1
  • do the elements of the list have the correct floating point number when you concatenate them? Commented Dec 4, 2014 at 17:37

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

1

You are probably looking for struct.unpack.

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.