On Sun, 19 Sep 2010 13:39:38 -0400, Bradley Mitchell <abstracta...@gmail.com> wrote:

Hello,

I'm trying to implement the Quake 3 fast inverse square root algorithm which requires casting from int to float without modifying the stored bits. A C++ reinterpret cast seems to accomplish this just fine but so far I have had no success in D after trying quite a few different things. Here is the C++ I've
written that currently works:

#include <iostream>

float fastInvSqrt( float x )
{
    const int INV_SQRT_N = 1597292357;
    const float MULT = 1.000363245811462f;

    float const mx = 0.5f * MULT * x;
    int xi = *reinterpret_cast<int *>( &x );

Note the use of pointers and address above?

    xi = INV_SQRT_N - (xi >> 1);
    x = *reinterpret_cast<float *>( &xi );
    return x * (1.5f * MULT - mx * x * x);
}

int main()
{
    float a = fastInvSqrt( 9.0f );
    std::cout << a << std::endl;
}

And here is my D code that doesn't work yet:

module test;

import std.stdio;

float fastInvSqrt( float x )
{
    const int INV_SQRT_N = 1597292357;
    const float MULT = 1.000363245811462f;

    float mx = 0.5f * MULT * x;
    int xi = cast(int)cast(void*)x;

You forgot that here...

int xi = *cast(int *)(&x);

rule of thumb -- if you want to do a reinterpret cast, you usually must take the address first. The compiler never tries anything tricky on pointer casts.

-Steve

Reply via email to