3.1 Byte Ordering
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, one would need to implement metafile record processing so that it could read integers from a file based on the endian method that the computer uses.