Determining CPU endianness at runtime
Since the short 1 is represented as 00 00 00 01 on big endian machines and 01 00 00 00 on little endian machines, it’s a rather straight forward matter to detect the endianness of a machine, by simply looking at how it stores a short.
#include <stdio.h> int main() { unsigned short i = 1; // store a short char* p = (char*) &i; // convert the short into an array of bytes if (p[0] == 1) { // if the first byte is 01, then it's a little endian machine printf("Little endian\n"); } else { // otherwise, it's a big endian machine printf("Big endian\n"); } return 0; }