我有从硬件读取并返回的库函数
value = readregister(registerindex,numbytes)
其中 value
是一个 python 列表。
如果numbytes
为4,则返回完整的数字
value[0],value[1],value[2] and value[3]
寄存器中的实际值是一个 float 。 那么如何将这个包含 4 个元素的列表值转换为 python float 呢?
最佳答案
您需要先将四个字节的列表转换为 Python 字节字符串,然后将该字符串转换为浮点值。
假设您有列表 value = [0, 0, 192, 63]
.先转成字节串:
vstr = ''.join([chr(k) for k in slist]) #chr converts the integer into the corresponding byte
然后,作为dyoo points out你可以使用 struct.unpack将字节串转换为 float :
f = struct.unpack("f", vstr)
在这个例子中 f
是 1.5。
您需要注意的一件事是硬件设备的字节顺序。如果字节顺序与您进行解压的平台相反,则使用“f”作为格式字符串为 struct.unpack
会给出错误的答案。在格式字符串前加上 <
对于小端设备,和 >
对于大端设备:
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
关于python - 将python列表转换为float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27300315/