Reputation: 237
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
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