title: How to byteswap a double?
body: <p>I'm trying to write a byteswap routine for a C++ program running on Win XP. I'm compiling with Visual Studio 2008. This is what I've come up with:</p>
  
  <pre><code>int byteswap(int v) // This is good
  {
      return _byteswap_ulong(v);
  }
  
  double byteswap(double v) // This doesn't work for some values
  {
      union { // This trick is first used in Quake2 source I believe :D
          __int64 i;
          double  d;
      } conv;
      conv.d = v;
      conv.i = _byteswap_uint64(conv.i);
      return conv.d;
  }
  </code></pre>
  
  <p>And a function to test:</p>
  
  <pre><code>void testit() {
      double  a, b, c;
      CString str;
  
      for (a = -100; a &lt; 100; a += 0.01) {
          b = byteswap(a);
          c = byteswap(b);
          if (a != c) {
              str.Format("%15.15f %15.15f %15.15f", a, c, a - c);
          }
      }
  }
  </code></pre>
  
  <p>Getting these numbers not matching:</p>
  
  <pre>
  -76.789999999988126 -76.790000000017230 0.000000000029104  
  -30.499999999987718 -30.499999999994994 0.000000000007276  
  &nbsp;41.790000000014508 &nbsp;41.790000000029060 -0.000000000014552  
  &nbsp;90.330000000023560 &nbsp;90.330000000052664 -0.000000000029104
  </pre>
  
  <p>This is after having read through:<br>
  <a href="https://stackoverflow.com/questions/105252/how-do-i-convert-between-big-endian-and-little-endian-values-in-c">How do I convert between big-endian and little-endian values in C++?</a><br>
  <a href="https://stackoverflow.com/questions/4169424/little-endian-big-endian-problem">Little Endian - Big Endian Problem</a><br>
  You can't use &lt;&lt; and >> on double, by the way (unless I'm mistaken?)</p>