Strictly speaking, the only method that is completely ANSI C compliant would be to iterate over all possible int values and check that they all match the representation you want. However, if you can assume that all systems you'll be on are either little endian, big endian, or mixed endian (ie, nothing really weird like gray coding or BCD), you can just do something like this:
static const unsigned int testvec = 0x01020304;
static const unsigned char letest[4] = { 0x04, 0x03, 0x02, 0x01 };
static const unsigned char betest[4] = { 0x01, 0x02, 0x03, 0x04 };
int isle() {
return !memcmp(&testvec, letest, 4);
}
int isbe() {
return !memcmp(&testvec, betest, 4);
}
Note that if you do not look at the byte representation (ie, if you do not cast pointers to look at the raw bytes), you cannot tell what byte order is in use. 0x0001 & 0x1000
is 0
on all C implementations, because both 0x0001
and 0x1000
are equally byte-swapped (and because the little endian representation of 0x0001
is 01 00
, not 10 00
).