我在Christopher Ttremblay的“游戏程序员数学”一书中找到了以下代码。它看起来像c ++,并且确实对stllib进行了一系列性能比较的引用,因为给出的代码是这样的:
float Exp2(float X)
{
float Result, Square, IntPow;
if (X < 0) {
const unsigned long IntVal = *(unsigned long *)&X & 0x7FFFFFFF;
const unsigned long Int = (IntVal >> 23) - 127;
if ((long)Int > 0) {
*(unsigned long *)&IntPow = ((((IntVal & 0x007FFFFF) |
0x00800000) >> (23 - Int)) + 127 + 1) << 23;
*(unsigned long *)&X = (((IntVal << Int) & 0x007FFFFF)
| 0x3F800000);
X = 2.0f - X;
} else {
IntPow = 2.0f;
X++;
}
Result = X0CoEff + Square * X1CoEff;
Square *= X; // The 2 last lines are repeated for every coeff.
Result += Square * XiCoEff;
...
return Result / IntPow;
} else {
const unsigned long IntVal = *(unsigned long *)&X;
const unsigned long Int = (IntVal >> 23) - 127;
if ((long)Int > 0) {
*(unsigned long *)&IntPow = ((((IntVal & 0x007FFFFF) |
0x00800000) >> (23 - Int)) + 127) << 23;
*(unsigned long *)&X = (((IntVal << Int) & 0x007FFFFF)
| 0x3F800000);
X—;
} else
IntPow = 1.0f;
Square = X;
Result = X0CoEff + Square * X1CoEff;
Square *= X; // The 2 last lines are repeated for every coeff.
Result += Square * XiCoEff;
...
return Result * IntPow;
}
}
float log2(float X)
{
float Result, Square;
Result = (float)((*(unsigned long *)&X) >> 23) - 127 + x0CoEff;
*(unsigned long *)&X = (*(unsigned long *)&X & 0x007FFFFF) | 0x3F800000;
Square = X;
Result += Square * XiCoEff;
Square *= X; // The 2 last lines are repeated for every coeff.
...
return Result;
}
问题是我从未真正学过位操作(我认为这是正在发生的事情,如果不是,我仍然从未在编码任务中处理过十六进制)。如果有人可以通过评论或将其翻译成更高级别的c / c ++来理解,那么可能会有所帮助。
本书解释说,与stllib相比,这些函数应该是函数的优化版本,但正如您所看到的那样,代码没有得到很好的评论(这些行复制角色为字符)
答案 0 :(得分:0)
你真的不需要了解他们在做什么。如果你愿意,你可以在C中谷歌bithift运算符,并了解运算符正在做什么,但这可能无法帮助你理解代码。实际上,代码只包含非常棘手的方法来非常快速地执行操作。