c - Detecting Endianess -
c - Detecting Endianess -
i'm trying create c source code handles i/o whatever endianess of target system.
i've selected "little endian" i/o convention, means that, big endian cpu, need convert info while writing or reading.
conversion not issue. problem face observe endianess, preferably @ compile time (since cpu not alter endianess in middle of execution...).
up now, i've been using :
#if __byte_order__ == __order_little_endian__ ... #else ... #endif it's documented gcc pre-defined macro, , visual seems understand too.
however, i've received study check fails big_endian systems (powerpc).
so, i'm looking foolproof solution, ensures endianess correctly detected, whatever compiler , target system. well, of them @ least...
[edit] : of solutions proposed rely on "run-time tests". these tests may evaluated compilers during compilation, , hence cost no real runtime performance.
however, branching kind of << if (0) { ... } else { ... } >> not enough. in current code implementation, variable , functions declaration depend on big_endian detection. these cannot changed if statement.
well, obviously, there fall plan, rewrite code...
i prefer avoid that, but, well, looks diminishing hope...
[edit 2] : have tested "run-time tests", modifying code. although job correctly, these tests impact performance.
i expecting that, since tests have predictable output, compiler eliminate bad branches. unfortunately, doesn't work time. msvc compiler, , successful in eliminating bad branches, gcc has mixed results, depending on versions, kind of tests, , greater impact on 64 bits on 32 bits.
it's strange. , means run-time tests cannot ensured dealt compiler.
instead of looking compile-time check, why not utilize big-endian order (which considered "network order" many) , utilize htons/htonl/ntohs/ntohl functions provided unix-systems , windows. they're defined job you're trying do. why reinvent wheel?
c preprocessor endianness compile-time
Comments
Post a Comment