【问题标题】:Interpret list of integers as a float in Python在 Python 中将整数列表解释为浮点数
【发布时间】:2013-06-29 05:54:03
【问题描述】:

我正在尝试将 C 代码 sn-p 转换为 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个整数,例如。 0 0 66 134 输出为 1 个浮点数,例如。 1.xxxxx * 10^yyyyy

标签: python c pointers type-conversion


【解决方案1】:

使用struct modulef 格式字符

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    相关资源
    最近更新 更多