Reputation: 31
I am attempting to convert a C code snippet into python.
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) ;
}
Is there some Python magic that can perform this function cleanly?
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?
This got me what I needed:
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
Upvotes: 2
Views: 800
Reputation: 304205
Use the struct module with the f
format character
>>> import struct
>>> plc_real = "1234"
>>> struct.unpack("f", plc_real)[0]
1.6688933612840628e-07
Make sure you use <
or >
to set the endianness you need
Upvotes: 4