Is there a one line macro definition to determine the endianness of the machine. I am using the following code but converting it to macro would be too long.
unsigned char test_endian( void )
{
int test_var = 1;
unsigned char test_endian* = (unsigned char*)&test_var;
return (test_endian[0] == NULL);
}
If you are looking for a compile time test and you are using gcc, you can do:
See gcc documentation for more information.
I believe this is what was asked for. I only tested this on a little endian machine under msvc. Someone plese confirm on a big endian machine.
As a side note (compiler specific), with an aggressive compiler you can use "dead code elimination" optimization to achieve the same effect as a compile time
#if
like so:The above relies on the fact that the compiler recognizes the constant values at compile time, entirely removes the code within
if (false) { ... }
and replaces code likeif (true) { foo(); }
withfoo();
The worst case scenario: the compiler does not do the optimization, you still get correct code but a bit slower.The 'C network library' offers functions to handle endian'ness. Namely htons(), htonl(), ntohs() and ntohl() ...where n is "network" (ie. big-endian) and h is "host" (ie. the endian'ness of the machine running the code).
These apparent 'functions' are (commonly) defined as macros [see <netinet/in.h>], so there is no runtime overhead for using them.
The following macros use these 'functions' to evaluate endian'ness.
In addition:
The only time I ever need to know the endian'ness of a system is when I write-out a variable [to a file/other] which may be read-in by another system of unknown endian'ness (for cross-platform compatability) ...In cases such as these, you may prefer to use the endian functions directly:
Whilst there is no portable #define or something to rely upon, platforms do provide standard functions for converting to and from your 'host' endian.
Generally, you do storage - to disk, or network - using 'network endian', which is BIG endian, and local computation using host endian (which on x86 is LITTLE endian). You use
htons()
andntohs()
and friends to convert between the two.Quiet late but... If you absolutely must have a macro AND ultra-portable code, detect and set it from your built environment (cmake/autotools).
Here's a simple program to just get it done, suitable for grepping:
Macro to find endiannes
or