views:

127

answers:

3

I've got a python webserver where small binary files are POST:ed. The posted data is represented as strings. I want to examine the contents of these strings. But to do that, I need to convert each 4 bytes to floats (little endian). How do you do that?

+6  A: 

You use the struct module:

>>> import struct
>>> struct.unpack_from("f", "\43\a3\12\32")
(8.6198787687447256e-33,)
unwind
Thanks, this works.
quano
+1  A: 

The construct module might also be a handy way to do this. It should be easy to adapt this example to your needs:

# [U]nsigned, [L]ittle endian, 16 bit wide integer (parsing)
>>> ULInt16("foo").parse("\x01\x02")
513
biocs
+5  A: 

While struct is best for unpacking collection of "scalar" binary values, when you what you have is a sequence of 4-byte binary floats in a string one after the other, the array module is ideal. Specifically, it's as simple as:

import array
thefloats = array.array('f', thestring)

If only part of thestring contains the sequence of 4-byte binary floats, you can build the array from that part by using the appropriate slice of the string instead of the entire string. The array instance offers most of the functionality of list (plus handy methods to convert to/from strings of bytes and swap between little-endian and big-endian forms if needed), but it's less flexible (only floats can be in the array) and enormously more compact (can take up 3-4 times less memory than a list with the same items).

Alex Martelli
Wow, this was very easy and powerful.
quano
@quano, glad to have been of help!
Alex Martelli