title: Detecting Endianness
body: <p>I'm currently trying to create a <strong>C</strong> source code which properly handles I/O whatever the endianness of the target system.</p>
  
  <p>I've selected "little endian" as my I/O convention, which means that, for big endian CPU, I need to convert data while writing or reading.</p>
  
  <p>Conversion is not the issue. The problem I face is to detect endianness, preferably at compile time (since CPU do not change endianness in the middle of execution...).</p>
  
  <p>Up to now, I've been using this :</p>
  
  <pre><code>#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
  ...
  #else
  ...
  #endif
  </code></pre>
  
  <p>It's documented as a GCC pre-defined macro, and Visual seems to understand it too.</p>
  
  <p>However, I've received report that the check fails for some big_endian systems (PowerPC).</p>
  
  <p>So, I'm looking for a foolproof solution, which ensures that endianess is correctly detected, whatever the compiler and the target system. well, most of them at least...</p>
  
  <p>[Edit] : Most of the solutions proposed rely on "run-time tests". These tests may sometimes be properly evaluated by compilers during compilation, and therefore cost no real runtime performance.</p>
  
  <p>However, branching with some kind of &lt;&lt; <code>if (0) { ... } else { ... }</code> >> is not enough. In the current code implementation, variable and functions <strong>declaration</strong> depend on big_endian detection. These cannot be changed with an if statement.</p>
  
  <p>Well, obviously, there is fall back plan, which is to rewrite the code...</p>
  
  <p>I would prefer to avoid that, but, well, it looks like a diminishing hope...</p>
  
  <p>[Edit 2] : I have tested "run-time tests", by deeply modifying the code. Although they do their job correctly, these tests also impact performance. </p>
  
  <p>I was expecting that, since the tests have predictable output, the compiler could eliminate bad branches. But unfortunately, it doesn't work all the time. MSVC is good compiler, and is successful in eliminating bad branches, but GCC has mixed results, depending on versions, kind of tests, and with greater impact on 64 bits than on 32 bits.</p>
  
  <p>It's strange. And it also means that the run-time tests cannot be ensured to be dealt with by the compiler.</p>
  
  <p><strong>Edit 3</strong> : These days, I'm using a compile-time constant union, expecting the compiler to solve it to a clear yes/no signal.
  And it works pretty well :
  <a href="https://godbolt.org/g/DAafKo" rel="noreferrer">https://godbolt.org/g/DAafKo</a></p>