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);
}
You can in fact access the memory of a temporary object by using a compound literal (C99):
Which GCC will evaluate at compile time.
Try this:
Code supporting arbitrary byte orders, ready to be put into a file called
order32.h
:You would check for little endian systems via
If you want to only rely on the preprocessor, you have to figure out the list of predefined symbols. Preprocessor arithmetics has no concept of addressing.
GCC on Mac defines
__LITTLE_ENDIAN__
or__BIG_ENDIAN__
Then, you can add more preprocessor conditional directives based on platform detection like
#ifdef _WIN32
etc.There is no standard, but on many systems including
<endian.h>
will give you some defines to look for.Don't forget that endianness is not the whole story - the size of
char
might not be 8 bits (e.g. DSP's), two's complement negation is not guaranteed (e.g. Cray), strict alignment might be required (e.g. SPARC, also ARM springs into middle-endian when unaligned), etc, etc.It might be a better idea to target a specific CPU architecture instead.
For example:
Note that this solution is also not ultra-portable unfortunately, as it depends on compiler-specific definitions (there is no standard, but here's a nice compilation of such definitions).