Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to do a C++ style compile-time assertion to determine machine's endianness?

I have some low level serialization code that is templated, and I need to know the system's endianness at compiletime obviously (because the templates specializes based on the system's endianness).

Right now I have a header with some platform defines, but I'd rather have someway to make assertions about endianness with some templated test (like a static_assert or boost_if). Reason being my code will need to be compiled and ran on a wide range of machines, of many specialized vendor, and probably devices that don't exist in 2008, so I can't really guess what might need to go into that header years down the road. And since the code-base has an expected lifetime of about 10 years. So I can't follow the code for-ever.

Hopefully this makes my situation clear.

So does anyone know of a compile-time test that can determine endianness, without relying on vendor specific defines?

like image 832
Robert Gould Avatar asked Nov 11 '08 06:11

Robert Gould


People also ask

How do you measure Endianness?

If it is little-endian, it would be stored as “01 00 00 00”. The program checks the first byte by dereferencing the cptr pointer. If it equals to 0, it means the processor is big-endian(“00 00 00 01”), If it equals to 1, it means the processor is little-endian (“01 00 00 00”).


2 Answers

If you're using autoconf, you can use the AC_C_BIGENDIAN macro, which is fairly guaranteed to work (setting the WORDS_BIGENDIAN define by default)

alternately, you could try something like the following (taken from autoconf) to get a test that will probably be optimized away (GCC, at least, removes the other branch)

int is_big_endian() {     union {         long int l;         char c[sizeof (long int)];     } u;      u.l = 1;      if (u.c[sizeof(long int)-1] == 1)     {         return 1;     }     else         return 0; } 
like image 57
Hasturkun Avatar answered Sep 23 '22 08:09

Hasturkun


There is no portable way to do this at compile time, your best bet is probably to use the Boost endian macros or emulate the methods they use.

like image 39
Robert Gamble Avatar answered Sep 22 '22 08:09

Robert Gamble