struct.unpack() and bit operations

Peter Hansen peter at engcorp.com
Thu Sep 23 12:33:28 EDT 2004


mikeSpindler wrote:
> THANKS FOR THE HELP ON MY LAST INQUIRY!  AWESOME ANSWERS.
> 
> I am reading in from a binary file data that is formatted as 32 *
> 16-bit words.  So when I read it in I'm apparently not getting or
> addressing correctly the upper 16-bits (since I have no choice but
> read 32-bit elements - right?).

You can read any amount of data that you want, including bytes.
Use read(n) where n is the number of bytes to grab.

> Is there an easier way to either get 16-bit "unpacks" or grab the
> upper 16-bits with success?

Not sure why you're having troubles: there are many ways of unpacking
stuff using struct, and it will handle bytes, words (16-bit values),
and 32-bit values, with the two popular variations on the endianism
of the data handled, and other things.

> Here's what I'm trying:
> 
> mask0 = 1111111100000000
> mask1 = 0000000011111111
> 
> pdr32 = struct.unpack('%si' % (itemsize/4), pdrData.read(itemsize))

Does pointing out that there is an "h" specified in addition to "i"
help you?  In the docs, "short" refers to a 16-bit value.

-Peter



More information about the Python-list mailing list