我正在尝试将 C 代码片段转换为 python。
该函数的目的是从 PLC 获取 4、8 位读数,并将它们解码为单个 float 。
float conv_float_s7_pc(char * plc_real)
{
char tmp[4];
tmp[0] = * (plc_real + 3);
tmp[1] = * (plc_real + 2);
tmp[2] = * (plc_real + 1);
tmp[3] = * (plc_real + 0);
return (* (float *) tmp) ;
}
是否有一些 Python 魔法可以干净地执行此功能?
当我尝试转换上述函数时,更普遍的问题是,如何在 python 中执行这样的内存“重新解释”?
编辑
这给了我我需要的东西:
import struct
def conv_to_float(plc):
temp = struct.pack("BBBB", plc[0], plc[1], plc[2], plc[3])
output = struct.unpack(">f", temp)[0]
return output
最佳答案
使用struct module与 f
格式字符
>>> import struct
>>> plc_real = "1234"
>>> struct.unpack("f", plc_real)[0]
1.6688933612840628e-07
确保您使用<
或>
设置您需要的字节顺序
关于python - 在 Python 中将整数列表解释为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17415850/