Unusual conversion between float and long

I found a very complex function, this is an implementation of the fast inverse square root. I honestly don't understand how this function works, but the following conversion between longand floatcaught my eye:

i  = *(long *) &y; 

And I leave the full code

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

    x2 = number * 0.5F;
    y  = number;
    i  = *(long *) &y;                      
    i  = 0x5f3759df - (i >> 1);            
    y  = * (float *) &i;
    y  = y * (threehalfs - (x2 * y * y));  

    return y;
}
+4
source share
1 answer

Listing just reinterprets bits ylike longso that he can perform on them integer arithmetic.

See Wikipedia for an explanation of the algorithm: Fast inverse square root .

The code uses knowledge of what's on the target platform sizeof(long) == sizeof(float).

@R.. :

C-it a . memcpy, , ( , , ) union a > . OP- " " (.. ) .

, , .

+7

Source: https://habr.com/ru/post/1569902/


All Articles