Coaxing DWORD values out of a Binary file...

Bengt Richter bokr at oz.net
Tue Nov 26 12:28:50 EST 2002


On Tue, 26 Nov 2002 08:37:16 GMT, "Fredrik Lundh" <fredrik at pythonware.com> wrote:

>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:
In this case "people" was me, I think. I could have made the same guess you did,
but I chose not to.

>
>    struct.unpack("<I", data)
>
>From what the OP says, he already tried some version of this, perhaps exactly this.
We don't know.
>(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)
Presumably the OP tried some code close to this also. I guessed that the OP had
read the struct module docs, and not opening in binary was the most likely problem,
which I mentioned, albeit in the context of a complaint.
>
>to debug, use "print repr(data)" or "print data.encode('hex')" and
>make sure the data is what you expect it to be.
>
This is good specific advice, which I also suggested in a general way.

I am a bit chastened, and will try to improve my tone, but I think I will
continue to noodge people about posting snippets of actual interactive experiments
demonstrating their problems instead of creating unnecessary ("lame" ;-) guesswork.

Regards,
Bengt Richter



More information about the Python-list mailing list