rsp rsp - 8 months ago 72
C Question

What does i = * ( long * ) &y; do?

I saw following code here.

float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;

x2 = number * 0.5F;
y = number;
i = * ( long * ) &y; // evil floating point bit level hacking
i = 0x5f3759df - ( i >> 1 ); // what the heck?
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed

return y;
}


I don't understand following line.

i = * ( long * ) &y;


Generally, we use
*
and
&
with pointer, but here both used with variable. So, what does it do here?

Answer Source

The line is taking a float, looking at the memory holding that float, reinterpreting that memory as memory holding a long, and getting that long. Basically, it's reinterpreting the bit-pattern of a floating point number as that of an integer, in order to mess around with its bits.

Unfortunately, that code is also wrong. You are not allowed to dereference that casted pointer, for reasons described here. In C, the one-and-only way of reinterpreting a bit pattern is through memcpy. (Depending on C variant and implementation, going through a union may be acceptable as well.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download