-1

I have a file that contains the raw data for an array of 32-bit floats. I would like to read this data and resemble it to floats and store them in a list.

enter image description here

How can I do this using python?

Note: The data originates from an embedded device that may use a different endian than my desktop.

Q-bertsuit
  • 3,223
  • 6
  • 30
  • 55

2 Answers2

1

The standard struct module is good for dealing with packed binary data like this. Here's a quick example:

dataFromFile = "\x67\x66\x1e\x41\x01\x00\x30\x41"   # an excerpt from your data

import struct
numFloats = len(dataFromFile) // 4

# Try decoding it as little-endian
print(struct.unpack("<" + "f" * numFloats, dataFromFile))
# Output is (9.90000057220459, 11.000000953674316)

# Try decoding it as big-endian
print(struct.unpack(">" + "f" * numFloats, dataFromFile))
# Output is (1.0867023771258422e+24, 2.354450749630536e-38)

The little-endian interpretation looks a lot more meaningful in this case (9.9 and 11, with the usual floating-point inaccuracies), so I guess that's the actual format.

jasonharper
  • 9,450
  • 2
  • 18
  • 42
0

you can read it the file, store it in a string then parse the string and convert to float:

with open(“testfile.txt”) as file:  
    data = file.read() 
    values = data.split(" ")
    floatValues = [float(x) for x in values]

or you can use some parser from the numpy module or the csv reading files modules

Petronella
  • 2,327
  • 1
  • 15
  • 24
  • Thank you for answering! I think your solution works with data stored as ASCII separated by spaces? My data is not stored as ASCII. – Q-bertsuit Feb 14 '18 at 14:26
  • this might be helpful then, use an encoding type for reading the data: https://stackoverflow.com/questions/147741/character-reading-from-file-in-python – Petronella Feb 15 '18 at 12:22