views:

1476

answers:

5

I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?

A: 

Edit: Forget what I said. But it looks like GotAPI has what you are looking for.

GotAPI is a great resource for finding out all those built in functions that you may not already know about.

DanV
+10  A: 

You want the struct package.

Patrick
Add a bit of demonstration code and I'll upvote.
John Mulder
+9  A: 
>>> import struct
>>> struct.pack('f', 3.141592654)
'\xdb\x0fI@'
>>> struct.unpack('f', '\xdb\x0fI@')
(3.1415927410125732,)
>>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0)
'\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@'
ΤΖΩΤΖΙΟΥ
+1  A: 

You should definitely give Construct a try. Like struct it allows to translate binary data to Python object and vice versa, but offers a lot more features.

Really great for parsing protocol data, legacy binary file formats and such.

Ber
A: 

Hi everybody, how could I do the inverse operation? i.e, in my case, i need to convert a float to a 4 byte array?

Javier