By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,911 Members | 1,147 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,911 IT Pros & Developers. It's quick & easy.

Unpacking problem

P: n/a
What's wrong here?
>>from struct import unpack
I can unpack an unsigned char
>>unpack('B','\x90')
(144,)

I can unpack a short
>>unpack('h','\x06\x00')
(6,)

But an unsigned char & a short give me this
>>unpack('Bh','\x90\x06\x00')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
struct.error: unpack str size does not match format
>>>
Mar 1 '07 #1
Share this Question
Share on Google+
3 Replies


P: n/a
In <11*********************@h3g2000cwc.googlegroups.c om>, Chris Garland
wrote:
But an unsigned char & a short give me this
>>>unpack('Bh','\x90\x06\x00')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
struct.error: unpack str size does not match format
Let's pack this:

In [90]: pack('Bh', 0x90, 0x6)
Out[90]: '\x90\x00\x06\x00'

Per default the values are (un)packed with the preferred alignment of the
C compiler, so here is an extra byte to place the short at an even
address. If you give the endianess in the format string there's no
padding:

In [91]: pack('<Bh', 0x90, 0x6)
Out[91]: '\x90\x06\x00'

Ciao,
Marc 'BlackJack' Rintsch
Mar 1 '07 #2

P: n/a
The problem is, that len('\x90\x06\x00') is not equivalent to
calcsize('Bh'):
>>calcsize('Bh')
4
>>len('\x90\x06\x00')
3

Actually calculating the size for 'hB' results in:
>>calcsize('hB')
3

So far I have not figured out, why there is an additional byte, but it
does not effect the result in any way. (Or I simply did not insert any
byte that would cause an effect.)

So
>>unpack('Bh', '\x90\x??\x06\x00')
(144,6)

with ?? as any valid hex, gives the "correct" result, but I dont know
why either.

On Mar 1, 10:17 pm, "Chris Garland" <chrisgarlan...@gmail.comwrote:
What's wrong here?
>from struct import unpack

I can unpack an unsigned char>>unpack('B','\x90')

(144,)

I can unpack a short>>unpack('h','\x06\x00')

(6,)

But an unsigned char & a short give me this>>unpack('Bh','\x90\x06\x00')

Traceback (most recent call last):
File "<stdin>", line 1, in ?
struct.error: unpack str size does not match format


Mar 1 '07 #3

P: n/a
Ok, that solves my confusion.
Thanks, Marc.

Mar 1 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.