将整数列表解释为Python中的float

我试图将C代码段转换为python。

所述function的目的是从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) ; } 

是否有一些可以干净地执行此function的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 

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

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

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