Reading binary data

nntpman68 news1234 at free.fr
Wed Sep 10 17:09:54 EDT 2008


What I would do first is to print the result byte by byte each as 
hexadecimal number.

If you can I would additionally populate the C-structure with numbers, 
which are easier to follow.

Example:

signature = "ABC"  // same as 0x41 0x42 0x43
version = 0x61626364
attr_count = 0x65667678
. . .

assuming version == 2 (0x00000002)
the first byte should be 'G' == 0x47 )
if the 4th byte value 2, than you unaligned uint32s and you are little 
endian
if the 5th byte is 2, then you have 4 byte aligned uint32s and little endian
if the 7th byte is 2 then you should have unaligned uint32s and big endian
if the 8th byte is 2 then you should have 4 byte aligned uints32 and big 
endian


bye

N


Aaron Scott wrote:
> I've been trying to tackle this all morning, and so far I've been
> completely unsuccessful. I have a binary file that I have the
> structure to, and I'd like to read it into Python. It's not a
> particularly complicated file. For instance:
> 
> signature   char[3]     "GDE"
> version     uint32      2
> attr_count  uint32
> {
>     attr_id         uint32
>     attr_val_len    uint32
>     attr_val        char[attr_val_len]
> } ... repeated attr_count times ...
> 
> However, I can't find a way to bring it into Python. This is my code
> -- which I know is definitely wrong, but I had to start somewhere:
> 
> import struct
> file = open("test.gde", "rb")
> output = file.read(3)
> print output
> version = struct.unpack("I", file.read(4))[0]
> print version
> attr_count = struct.unpack("I", file.read(4))[0]
> while attr_count:
> 	print "---"
> 	file.seek(4, 1)
> 	counter = int(struct.unpack("I", file.read(4))[0])
> 	print file.read(counter)
> 	attr_count -= 1
> file.close()
> 
> Of course, this doesn't work at all. It produces:
> 
> GDE
> 2
> ---
> é
> ---
> ê Å
> 
> I'm completely at a loss. If anyone could show me the correct way to
> do this (or at least point me in the right direction), I'd be
> extremely grateful.



More information about the Python-list mailing list