【发布时间】:2011-02-09 18:51:39
【问题描述】:
我正在尝试为在 Win XP 上运行的 C++ 程序编写字节交换例程。我正在使用 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
顺便说一句,你不能在 double 上使用 >(除非我弄错了?)
【问题讨论】:
-
您能否澄清一下 Quake 2 中究竟发明了什么?肯定不是将 double 和 int64 作为同一个联合的字段的想法吗?
-
抱歉.. 我从 Quake2 中学到了 C,所以我喜欢假装它是最棒的 :D 我现在到处都看到它(联合)。
标签: c++ visual-studio-2008 endianness