2

我正在尝试将 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
4

1 回答 1

4

使用带有格式字符的结构模块f

>>> import struct
>>> plc_real = "1234"
>>> struct.unpack("f", plc_real)[0]
1.6688933612840628e-07

确保使用<>设置所需的字节序

于 2013-07-02T01:19:19.223 回答