c++ - How to byteswap a double? -


i'm trying write byteswap routine c++ program running on win xp. i'm compiling visual studio 2008. i've come with:

int byteswap(int v) // {     return _byteswap_ulong(v); }  double byteswap(double v) // doesn't work values {     union { // trick first used in quake2 source believe :d         __int64 i;         double  d;     } conv;     conv.d = v;     conv.i = _byteswap_uint64(conv.i);     return conv.d; } 

and function test:

void testit() {     double  a, b, c;     cstring str;      (a = -100; < 100; += 0.01) {         b = byteswap(a);         c = byteswap(b);         if (a != c) {             str.format("%15.15f %15.15f %15.15f", a, c, - c);         }     } } 

getting these numbers not matching:

 -76.789999999988126 -76.790000000017230 0.000000000029104   -30.499999999987718 -30.499999999994994 0.000000000007276    41.790000000014508  41.790000000029060 -0.000000000014552    90.330000000023560  90.330000000052664 -0.000000000029104 

this after having read through:
how convert between big-endian , little-endian values in c++?
little endian - big endian problem
can't use << , >> on double, way (unless i'm mistaken?)

although double in main memory 64 bits, on x86 cpus double-precision registers 80 bits wide. if 1 of values stored in register throughout, other makes round-trip through main memory , truncated 64 bits, explain small differences you're seeing.

maybe can force variables live in main memory taking address (and printing it, prevent compiler optimizing out), i'm not guaranteed work.


Comments