我正在尝试将C代码片段转换为python。
上述功能的目的是从PLC获取4,8位读数,并将其解码为单个浮点数。
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发布于 2013-07-02 09:19:19
使用带有f格式字符的struct module
>>> import struct
>>> plc_real = "1234"
>>> struct.unpack("f", plc_real)[0]
1.6688933612840628e-07确保使用<或>设置所需的字节顺序
https://stackoverflow.com/questions/17415850
复制相似问题