Conversion of 24bit binary to int

Patrick Maupin pmaupin at speakeasy.net
Tue Nov 11 21:26:39 EST 2003


Idar wrote:

> Is there an effecient/fast way in python to convert binary data from file 
> (24bit hex(int) big endian) to 32bit int (little endian)? Have seen 
> struct.unpack, but I am unsure how and what Python has to offer. Idar

As Peter mentions, you haven't _really_ given enough information
about what you need, but here is some code which will do what
I _think_ you said you want...

This code assumes that you have a string (named teststr here)
in the source format you describe.  You can get a string
like this in several ways, e.g. by reading from a file object.

This code then swaps every 3 characters and inserts a null
byte between every group of three characters.

The result is in a list, which can easily be converted back
to a string by ''.join() as shown in the test printout.

I would expect that either the array module or Numpy would
work faster with _exactly_ the same technique, but I'm
not bored enough to check that out right now.

If this isn't fast enough after using array or NumPy (or
after Alex, Tim, et al. get through with it), I would
highly recommend Pyrex -- you can do exactly the same
sorts of coercions you were doing in your C++ code.


teststr = ''.join([chr(i) for i in range(128,128+20*3)])

result = len(teststr) * 4 // 3 * [chr(0)]
for x in range(3):
    result[2-x::4] = teststr[x::3]

print repr(''.join(result))


Regards,
Pat




More information about the Python-list mailing list