D equivalent of C++ reinterpret cast?
Simen kjaeraas
simen.kjaras at gmail.com
Sun Sep 19 10:57:30 PDT 2010
Bradley Mitchell <abstractant1 at gmail.com> wrote:
> int xi = cast(int)cast(void*)x;
[...]
> x = cast(float)cast(void*)xi;
The simple solution (seeing as how x is an lvalue) is
int xi = *cast(int*)&x;
[...]
x = *cast(float*)ξ
Function version:
T reinterpret( T, U )( U value ) {
return *cast( T* )&value;
}
There may be situations in which this will not work (though
I know of none, OTOH), and where using a union will:
T reinterpret( T, U )( U value ) {
union Uni {
U u;
T t;
}
return Uni(value).t;
}
Of course, these are general solutions, and the easy solution
to your problem is to use a union directly:
float fastInvSqrt( float x ) {
enum int INV_SQRT_N = 1597292357;
enum float MULT = 1.000363245811462f;
float mx = 0.5f * MULT * x;
union Xu {
float f;
int i;
}
Xu xu = Xu(x);
xu.i = INV_SQRT_N - (xu.i >> 1);
return xu.f * (1.5f * MULT - mx * xu.f * xu.f);
}
--
Simen
More information about the Digitalmars-d-learn
mailing list