将整数列表解释为Python中的浮点数 [英] Interpret list of integers as a float in Python
本文介绍了将整数列表解释为Python中的浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将C代码片段转换为python.
I am attempting to convert a C code snippet into python.
该功能的目的是从PLC读取4个8位读数,并将其解码为单个浮点数.
The purpose of said function is to take 4, 8-bit readings from a PLC, and decode them into a single 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魔术可以干净地执行此功能?
Is there some Python magic that can perform this function cleanly?
当我尝试转换上述函数时,更笼统的问题是,您将如何在python中执行诸如此类的内存重新解释"?
While I am attempting to convert the above function, the more general question is, how would you perform memory "reinterpretations" such as this in 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
推荐答案
查看全文