[Tutor] Need help with structure unpacking module

Alan Gauld alan.gauld at btinternet.com
Tue Mar 18 15:14:26 CET 2008


"Nirmal Sakthi" <yennes at gmail.com> wrote

> I want to be able to extract a string.
>
> I have tried,
>
>    >>>first = struct.unpack('s', '\x02\x00')
>    >>>first = str(first[0])
>    >>>print first
>    Traceback (most recent call last):
> ......
>    error: unpack requires a string argument of length 1

Which is correct because you asked for a string
of length 1 but fed it 2 bytes

>    >>>first = struct.unpack('cccc', '\x02\x00')
>    >>>first = str(first[0])
>    >>>print first
>     Traceback (most recent call last):
> ......
>         return o.unpack(s)
>     error: unpack requires a string argument of length 4

And here you asked for 54 characters but only gave
it two bytes.  And the two byes were 02 and 00 which
are not printable characters.

> My desired result would be the string  '0200'.

To get that string you would need to feed that string in:

To see what that string looks like we need to use
the ord() function:

>>> for c in '0200': print hex(ord(c))
...
0x30
0x32
0x30
0x30
>>>

So your string needs to be:

'\x30\x32\x30\x30'

Now in struct:

>>> struct.unpack('4s','\x30\x32\x30\x30')
('0200',)
>>>

> Actually, I would like to be able to invert the bytes to get '0002'.

Well, in that case you ned to feed struct with 0002:

>>> struct.unpack('4s','\x30\x30\x30\x32')
('0002',)
>>>

No magic in struct it reads out what you ask it to read
from the data you give it. It makes no attempt to guess
what the data means it asumes you as programmer
know what the data looks like and how to interpret
it properly. This of course means that when using
struct to extract data you need to validate that what
you got out matches what you expected to get!

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld






More information about the Tutor mailing list