[Tutor] Need help with structure unpacking module
Luke Paireepinart
rabidpoobear at gmail.com
Tue Mar 18 16:10:40 CET 2008
Nirmal Sakthi wrote:
> I am using module struct.unpack() to decode data from a binary file,
> so that I can use the value in a calculation.
>
> I have been able to extract an integer value.
>
> >>>length = struct.unpack('i', '\x9c\x00\x00\x00')
> >>>length = int(length[0])
> >>>print length
> 156
>
> 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
I believe you have to provide the string length for this, like
struct.unpack('2s', '\x02\x00') or something.
> and,
>
> >>>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
That's because \x02\x00 is only 2 characters long. You don't get direct
access to the hex, just to the characters.
vals = struct.unpack('cc','\x02\x00') #unpack values
>
> My desired result would be the string '0200'. Actually, I would like
> to be able to invert the bytes to get '0002'.
>>> x = ['a','b']
>>> x.reverse()
>>> x
['b', 'a']
Sorry I don't have more time to explain, I have to run to class.
HTH,
-Luke
More information about the Tutor
mailing list