3.1.2 Byte Ordering Example

The following code snippet illustrates how the use of the big-endian and little-endian methods can affect the compatibility of applications.

 #include <unistd.h>
 #include <sys/stat.h>
 #include <fcntl.h>
 int main()
 {
  int buf; 
  int in; 
  int nread;
  in = open("file.in", O_RDONLY); 
  nread = read(in, (int *) &buf, sizeof(buf));
  printf("First Integer in file.in = %x\n", buf);
  exit(0);
 }
  

In the preceding code, if the first integer word stored in the file.in file on a big-endian computer was the hexadecimal number 0x12345678, the resulting output on that computer would be as follows.

    % ./test
 First Integer in file.in = 12345678
 %
  

If the file.in file were read by the same program running on a little-endian computer, the resulting output would be as follows.

    % ./test
 First Integer in file.in = 78563412
 %
  

Because of the difference in output, metafile record processing can be implemented so that it can read integers from a file based on the endian method that the output computer uses.

Because metafiles were developed and written with little-endian computers, computers that are big-endian based will have to perform this necessary compensation.