quano
quano

Reputation: 19112

Read bytes from string as floats

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?

Upvotes: 1

Views: 4543

Answers (3)

Alex Martelli
Alex Martelli

Reputation: 881635

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).

Upvotes: 5

Michael Kuhn
Michael Kuhn

Reputation: 8972

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

Upvotes: 1

unwind
unwind

Reputation: 399813

You use the struct module:

>>> import struct
>>> struct.unpack_from("f", "\43\a3\12\32")
(8.6198787687447256e-33,)

Upvotes: 7

Related Questions