How can I determine whether a machines byte order is big-endian or little-endian?
The usual techniques are to use a pointer: int x = 1; if(*(char *)&x == 1) printf(“little-endian\n”); else printf(“big-endian\n”); or a union: union { int i; char c[sizeof(int)]; } x; x.i = 1; if(x.c[0] == 1) printf(“little-endian\n”); else printf(“big-endian\n”); (Note that there are also byte order possibilities beyond simple big-endian and little-endian[footnote] .) See also questions 10.16 and 20.9b. References: H&S Sec. 6.1.2 pp. 163-4 comp.lang.c FAQ list ยท Question 20.9b Q: How do I swap bytes? A: V7 Unix had a swab function, but it seems to have been forgotten. A problem with explicit byte-swapping code is that you have to decide whether to call it or not, based on the byte order of the data and the byte order of the machine in use. Question 20.9 shows how, but it’s a nuisance. A better solution is to define functions which convert between the known byte order of the data and the (unknown) byte order of the machine in use, and to arrange for these functions to be no-ops on thos