title: In c++, what is the best style for endian conversion
body: <p>I am making a library of inline functions for dealing with testing platform endianness and doing conversions..</p>
  
  <p>My first attempt was to structure the functions like this:</p>
  
  <pre><code>inline uint32_t NativeToLittle(uint32_t in)
  {
      if(littleEndian())
          return in;
      else
      {
          uint32_t var = 0;
          ((uint16_t*)&amp;var)[0] = NativeToLittle(((uint16_t*)&amp;in)[1]);
          ((uint16_t*)&amp;var)[1] = NativeToLittle(((uint16_t*)&amp;in)[0]);
  
          return var; 
      }
  }
  </code></pre>
  
  <p>This worked on some platforms, but on gcc with aggressive optimisation options, it fails (casting uint32_t* to uint16_t* ran afoul of the strict aliasing rules.)</p>
  
  <p>Given that the aliasing rules make a mention of unions, I rewrote the functions to use unions for conversion, like this:</p>
  
  <pre><code>inline uint32_t swapEndian(uint32_t in)
  {
      union ds
      {
          uint32_t a;
          uint16_t b[2];
      };
  
      ds var;
      ds out;
      var.a = in;
      out.b[0] = swapEndian(var.b[1]);
      out.b[1] = swapEndian(var.b[0]);
  
      return out.a;
  }
  </code></pre>
  
  <p>This worked on all platforms I've tried it on, but I'm not clear about whether it's good style. I recall seeing a video where the speaker said that this scheme of using unions for conversions was invalid because it was only valid to access one member of a union (I don't recall the url of this talk, sorry). Moreover, Stroustrup's JSF coding standards states that "unions shall not be used".</p>
  
  <p>The only other relevant thing in the aliasing rules is that casting to a char type is valid. Converting it to a char buffer and back is likely to be pretty ugly, though.</p>
  
  <p>So.. What is the best way to structure code like this which is both consistent with the standard and reasonably readable?</p>