Search code examples
c++translate

translating c/c++?


I found the following code in a book "Mathematics for Game Programmers" by Christopher Ttremblay. it looks like c++, and he does make a bunch of references to performance comparisons to the stllib the code given is as thus:

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;
}

the thing is I never actually learned bit operations (which I think is what is going on here, and if not I still never dealt with hex in my coding assignments). if someone could go through and maybe help by either commenting, or translating this to higher level c/c++ for understanding.

the book explains that these are supposed to be optimized versions of the functions compared to stllib, but as you can see the code is not very well commented (these lines where copied character for character)


Solution

  • You don't really need to understand what they're doing. If you want, you can google bitshift operators in C and understand what the operators are doing, but that probably won't help you here to understand the code. Really, the code just contains very tricky ways to do thing very very fast.