-1

Possible Duplicate:
John Carmack’s Unusual Fast Inverse Square Root (Quake III)

I came across this piece of code a blog recently - it is from the Quake3 Engine. It is meant to calculate the inverse square root fast using the Newton-Rhapson method.

float InvSqrt (float x){
    float xhalf = 0.5f*x;
    int i = *(int*)&x;
    i = 0x5f3759df - (i>>1);
    x = *(float*)&i;
    x = x*(1.5f - xhalf*x*x);
    return x;
}

What is the reason for doing int i = *(int*)&x;? Doing int i = (int) x; instead gives a completely different result.

Community
  • 1
  • 1
Omair
  • 754
  • 1
  • 9
  • 19
  • 10
    I'm pretty sure this is not an idiom among C programmers. – nos Aug 10 '10 at 19:01
  • 3
    Casting a `float` to an `int` is radically different than dereferencing a `float` pointer casted to an `int` pointer. Also, this method is much slower and less accurate than the `rsqrtss` x86 instruction. – zneak Aug 10 '10 at 19:06
  • 6
    I would argue that this is not really a duplicate, since it asks about the `*(int*)&x`, instead of the magic constant `0x5f3759df` which is the main focus of the other question. – David Z Aug 10 '10 at 19:21
  • 3
    http://assemblyrequired.crashworks.org/2009/10/16/timing-square-root/ It's true that this method is slower and less accurate than using the SSE rsqrt, but the code was written before SSE could be relied upon to be in a gamer's processor. – nmichaels Aug 10 '10 at 19:22

3 Answers3

7

int i = *(int*)&x; says "take the four bytes which make up the float value x, and treat them as if they were an int." float values and int value are stored using completely different methods (e.g. int 4 and float 4.0 have completely different bit patterns)

James Curran
  • 95,648
  • 35
  • 171
  • 253
7

int i = *(int*)&x; doesn't convert x to an int -- what it does is get the actual bits of the float x, which is usually represented as a whole other 4-byte value than you'd expect.

For reference, doing this is a really bad idea unless you know exactly how float values are represented in memory.

cHao
  • 78,897
  • 19
  • 136
  • 168
  • 4
    It's even more of a bad idea because the reinterpretation invokes undefined behavior and modern compiler writers love to just optimize it away. – Stephen Canon Aug 11 '10 at 18:02
2

The number that ends up in i is the binary value of the IEEE floating point representation of the number in x. The link explains what that looks like. This is not a common C idiom, it's a clever trick from before the SSE instructions got added to commercially available x86 processors.

nmichaels
  • 45,418
  • 12
  • 95
  • 127