我正在尝试为在Win XP上运行的C程序编写一个byteswap例程.我正在使用Visual Studio 2008编译.这就是我想出的:
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; }
还有一个测试功能:
void testit() { double a,b,c; CString str; for (a = -100; a < 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); } } }
获取这些数字不匹配:
-76.789999999988126 -76.790000000017230 0.000000000029104 -30.499999999987718 -30.499999999994994 0.000000000007276 41.790000000014508 41.790000000029060 -0.000000000014552 90.330000000023560 90.330000000052664 -0.000000000029104
这是在阅读完之后:
How do I convert between big-endian and little-endian values in C++?
Little Endian – Big Endian Problem
你不能使用<<和>>顺便说一下(除非我弄错了?)