If you desperately want to use the preprocessor, you could abuse string literals:
#include <stdint.h>
#define IS_BIG_ENDIAN (*(uint16_t *)"\0\xff" < 0x100)
As @microtherion notes in comments, this relies on string literals being correct aligned for access as uint16_t, which is not guaranteed. If you have a compiler that supports C99 compound literals, you can avoid this problem:
#define IS_BIG_ENDIAN (!*(unsigned char *)&(uint16_t){1})
or:
#define IS_BIG_ENDIAN (!(union { uint16_t u16; unsigned char c; }){ .u16 = 1 }.c)
In general though, you should try to write code that does not depend on the endianness of the host platform.
Example of host-endianness-independent implementation of ntohl():
uint32_t ntohl(uint32_t n)
{
unsigned char *np = (unsigned char *)&n;
return ((uint32_t)np[0] << 24) |
((uint32_t)np[1] << 16) |
((uint32_t)np[2] << 8) |
(uint32_t)np[3];
}
0instead ofNULLin your final test, and change one of thetest_endianobjects to something else :-). – Alok Singhal Jan 20 '10 at 9:48#ifdirective. – Rob Kennedy Apr 8 '10 at 5:08