Coaxing DWORD values out of a Binary file...

Fredrik Lundh fredrik at pythonware.com
Tue Nov 26 03:37:16 EST 2002


adeptus wrote:

> I've tried unpacking them via the struct module, (by passing them in as 4
> byte strings) but the numbers I get don't seem to make any sense for the
> file format...
>
> Am I making a naive assumption about how VC++ would write a DWORD to a
> binary file???
>
> I'm also assuming that:
>     (i386 centric)
>     8-Bits = 1 Char = 1 Byte
>     1 Word = 2 Bytes
>     1 DWORD = 4 Bytes
>
> What I'm asking is, what is proper officially pythonic way of accessing
> DWORD values stored in a binary file by a VC++ program???

for some reason, there seem to be a new trend on this newsgroup
where people post lame replies without even attempting to answer
the original question.  sorry for that.  here's the correct answer:

    struct.unpack("<I", data)

(little-endian, four-byte unsigned integer)

to avoid problems on non-Unix platforms, also make sure you open
the file in binary mode:

    f = open(filename, "rb")
    data = f.read(4)

to debug, use "print repr(data)" or "print data.encode('hex')" and
make sure the data is what you expect it to be.

</F>





More information about the Python-list mailing list