writing binary file for different platform

tinu tinu at email.ch
Mon May 13 03:16:53 EDT 2002


This is what I do for reading Fortran files produced on different
Machines. The line is taken from Numeric and is true (1) for little endian.

LittleEndian = Numeric.fromstring("\001"+"\000"*7, 'i')[0] == 1

I package the whole thing into one function that returns the appropriate
Fromstring function, depending on the hosts endianness as well as the file's
endianness:

-----

import Numeric

# this is taken from the Numeric.py module, where it is defined globally
# LittleEndian = Numeric.fromstring("\001"+"\000"*7, 'i')[0] == 1

def myFromstring(endian):
    """Handle the problems caused by endian types.
    o Big endian:    Sun Sparc, HP etc.
    o Little endian: Intel machines (PC)
    Give here the endian type of the file, the endian type of the machine
    is automatically determined by the constant LittleEndian above.
    The conventions are as those given in 'struct' module:
    '@','=' : File is native (was produced on the same machine)
    '<'     : File is little endian
    '>','!' : File is big endian (network)
    """

    if Numeric.LittleEndian:
        if endian in ['>','!']:
            return lambda s, t: Numeric.fromstring(s,t).byteswapped()
        else:
            return Numeric.fromstring
    elif endian in ['<']:
        return lambda s, t: Numeric.fromstring(s,t).byteswapped()
    else:
        return Numeric.fromstring

-- 
Martin Lüthi              VAW Glaciology, ETH Zürich, Switzerland
                          mel: luthi at vaw.baug.ethz.ch



More information about the Python-list mailing list