python - 在 Python 中将整数列表解释为 float

标签 python c pointers type-conversion

我正在尝试将 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 modulef格式字符

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

确保您使用<>设置您需要的字节顺序

关于python - 在 Python 中将整数列表解释为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17415850/

相关文章:

c++ - 指针比较 "<"与数组对象的最后一个元素

c - 在 DevC++ 中工作但不在 Visual studio 2017 中工作

c - C 中的 void 函数如何与指针一起使用?

matlab - 在MATLAB中将stringptrptr参数传递给C-DLL函数foo(char **)-清除指针会使MATLAB崩溃

Python pandas 通过 dt 访问器有效地将日期时间转换为时间戳

c - Getopt() 错误检查

python - 需要遍历字典以找到字符串片段

c - 为什么整型数组size(array)的返回值恰好是元素个数的4倍?

python - 为什么我收到额外的标签文本而不是我放入的实际标签?

java - 通过shell脚本运行maven项目和python文件