Help how do I read `word' variables from a binary file?

Steve Purcell stephen_purcell at yahoo.com
Mon Mar 26 08:27:21 EST 2001


nomad wrote:
> I can open the file without problems, and I can read from the file
> without a hitch, _BUT_ the trouble comes in that some of the data
> records in the file have fields that would be a double word or even a
> normal word in C++, so in effect the data may be 0x80002310, but
> python reads the data directly from the file, and as such is reading
> hex bytes as (in this example) `10 23 00 80' etc.  I'm sure that there
> must be a simple way to read in data like this, but I can't figure it
> out.


Look at the 'struct' module. For example, to read a network-byte-ordered word
(i.e. 2 bytes) from a stream you can use the following code:

    def readWord(self, stream):
        b2 = stream.read(2)     
        return struct.unpack('!H',b2)[0]

-Steve


-- 
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Any opinions expressed herein are my own and not necessarily those of Yahoo




More information about the Python-list mailing list