What does this idiom C mean?

Possible duplicate:
John Carmack & rsquo; Unusual fast reverse square root (Quake III)

I recently came across this piece of code - this is from Quake3 Engine. It is designed to quickly calculate the inverse square root using the Newton-Rapson 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 int i = *(int*)&x; ? Executing int i = (int) x; instead gives a completely different result.

0
source share
3 answers

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

For reference, doing this is very bad if you do not know exactly how the float values ​​are represented in memory.

+7
source

int i = *(int*)&x; says: "Take the four bytes that make up the float x value and treat them as if they were int." float values ​​and int values ​​are stored using completely different methods (for example, int 4 and float 4.0 have completely different bit patterns)

+7
source

A number that ends with i is the binary value of the IEEE floating point number at x. The link explains how it looks. This is no ordinary C idiom, it’s a smart trick before SSE instructions were added to commercially available x86 processors.

+2
source

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


All Articles