Re: Fortran unformatted data: Big or little endian [message #34952 is a reply to message #34951] |
Wed, 30 April 2003 07:48   |
Paul Van Delst[1]
Messages: 1157 Registered: April 2002
|
Senior Member |
|
|
Michael Schroeter wrote:
>
> Hi David,
>
> the problem is that I don't know the "endian nature" of the machine that
> created the data.
>
> In the meanwhile I tried using error catching, like shown in this
> code-snippet:
>
> array = FLTARR(100,100)
> OPENR, lun, data_file, /F77_UNFORMATTED, /GET_LUN
>
> CATCH, error_status
> IF error_status NE 0 THEN BEGIN
> PRINT, 'Error index: ', error_status
> PRINT, 'Error message: ', !ERROR_STATE.MSG
> FREE_LUN, lun
> OPENR, lun, data_file, /SWAP_ENDIAN, /F77_UNFORMATTED, /GET_LUN
> READU, lun, array
> CATCH, /CANCEL
> ENDIF ELSE BEIN
> READU, array
> ENDELSE
>
> and it works (up to now ;-)).
One possible solution:
Open the file as a "regular" binary file (i.e. no /F77_UNFORMATTED keyword)
OPENR, lun, data_file, /GET_LUN
Since the file is Fortran unformatted sequential output and you know the record size is
always 100x100 single precision (4 byte) floats then the first 4-bytes should be an
integer with the value 10000x4. Read this value and check it. If it's not 40000 then it
indicates the endian-ness is opposite of the default.
; -- Check the record size
RecordSize = 10000L * 4L
RecordSize_Test = 0L
READU, lun, RecordSize_Test
IF ( RecordSize_Test NE RecordSize ) THEN $
Swap = 1 $
ELSE $
Swap = 0
; -- Close the file
FREE_LUN, lun
; -- Open the file with the correct keywords
OPENR, lun, data_file, SWAP_ENDIAN=Swap, /F77_UNFORMATTED, /GET_LUN
READU, lun, array
....proceed with stuff.....
And the nice thing is this should work on big- and little-endian machine for either type
of file. (Aside: I really don't understand the usefulness of the
swap_if_little(big)_endian type of keyword.)
If you have access to the writing routines, one other way is to first write a "magic"
number to the data file - a PARAMETER (i.e. doesn't change) that you can check for. (You
may also want to write the dimensions too). Liam Gumley has some handly little utilities
for this in IDL (check his website). I've adopted those techniques for the flat binary
files I use in my Fortran95 code to identify the endian-ness of those files - nice and
simple and works every time.
The best solution (IMO) is to use platform independent data files (e.g. netCDF - my
favourite coz it relatively simple). Not always possible of course.
paulv
--
Paul van Delst
CIMSS @ NOAA/NCEP/EMC
Ph: (301)763-8000 x7748
Fax:(301)763-8545
|
|
|