struct.unpack() and bit operations

M

mikeSpindler

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

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

Here's what I'm trying:

mask0 = 1111111100000000
mask1 = 0000000011111111

pdr32 = struct.unpack('%si' % (itemsize/4), pdrData.read(itemsize))

while i < 32
pdr16[x] = (pdr32[y] & (mask0 / (2**8)))
pdr16[x+1] = (pdr32[y] & mask1)
x += 2
y += 1
pdrData.seek(32,1)


Thank you!
Mike Spindler
 
P

Peter Hansen

mikeSpindler said:
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
 
P

Peter Otten

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

You may have a look at the array module:
binary_data = "PleaseDon'tShout"
a = array.array("H", binary_data)
a array('H', [27728, 24933, 25971, 28484, 10094, 21364, 28520, 29813])
a[::2] array('H', [27728, 25971, 10094, 28520])
a[1::2].tostring() 'eaDotSut'

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top