将整数列表解释为Python中的浮点数 [英] Interpret list of integers as a float in Python

查看:121
本文介绍了将整数列表解释为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

推荐答案

使用

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

Make sure you use < or > to set the endianness you need

这篇关于将整数列表解释为Python中的浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆