Skip to content
Advertisement

Reading a C-struct via sockets into python

On an embedded device running a C application, I have defined this struct:

JavaScript

On request, I send this struct via sockets:

JavaScript

and read it from a Python script on my desktop:

JavaScript

This is the data printed to console on my desktop:

enter image description here

How can i reassemble the data into a YourStruct?

Note that the embedded device uses little endian, so I have had to use struct.unpack("<" + "f" * 2048, data) to reassemble an array of floats.

Advertisement

Answer

[Python.Docs]: struct – Interpret bytes as packed binary data contains all the needed intel.

code00.py:

JavaScript

Notes:

  • Starting from the point where the data (data) was received from the socket

  • The format passed to struct.unpack (fmt arg) tells it how the data is organized: in our case it’s "<fic": float, int, char (preceded by the little endian marker)

  • Also calculating the size (in bytes) of data that the format requires: it’s 9 (4 + 4 + 1). data has 12 bytes, so ignoring the last 3, otherwise struct.unpack will spit struct.error

  • Check [SO]: Python struct.pack() behavior for more details on struct.pack

Output:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement