Red Hat axp-list: Linux on Alpha (1995-2022)
 help / color / mirror / Atom feed
* Re: byte order, swapping code
@ 1998-06-16 13:54 Mike
  1998-06-16 14:40 ` Paul Tomblin
  0 siblings, 1 reply; 2+ messages in thread
From: Mike @ 1998-06-16 13:54 UTC (permalink / raw)
  To: axp-list


   If you don't mind creating a new data file with the swapped bytes
it is pretty easy.  Just read in the file as char's and write them out
in reverse order in sets of 2's, 4's, or 8's for 16 bit, 32 bit, and 64 bit
data.  But if the files are large and you frequently move back and forth
between architectures (like we do here, our Sun and Alpha both access the
same hard disk) you might want to do the conversion on the fly.

   The following is a function that will read a file of 32 bit floats
in either big or little endian format.  Our programs detect what architecture
they are running on and pass that info to the function as a flag.
size in this case is sizeof(float).

void fread_float(float *data, int size, int nitems, FILE *stream,int arch)
{ /* arch 0=don't swap, 1=we need to swap */
  
  union { char cval[4];  float fval; } sw;
  int i;
  char temp;

  if (arch)
    for (i=0;i<nitems;i++) {
      fread(sw.cval,size,1,stream);
      temp=sw.cval[0];  sw.cval[0]=sw.cval[3];
      sw.cval[3]=temp;  temp=sw.cval[1];
      sw.cval[1]=sw.cval[2];  sw.cval[2]=temp;
      data[i]=sw.fval;
    }
  else
    fread(data,size,nitems,stream);
}

   Hope this helps.

   Michael


^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~1998-06-16 14:39 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
1998-06-16 13:54 byte order, swapping code Mike
1998-06-16 14:40 ` Paul Tomblin

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox