什么是该C成语是什么意思? [英] What does this C idiom mean?
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/1349542/john-carmacks-unusual-fast-inverse-square-root-quake-iii\">John卡马克大局;不寻常的快速平方根倒数(雷神之锤III)
我穿过这片code一个博客的最近来了 - 这是从Quake3的引擎。它的目的是快速计算逆平方根使用牛顿 - Rhapson方法
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;
}
什么是做的原因INT I = *为(int *)及X;
?做 INT I =(int)的X;
,而不是给出一个完全不同的结果。
What is the reason for doing int i = *(int*)&x;
? Doing int i = (int) x;
instead gives a completely different result.
推荐答案
INT I = *(INT *)及X;
不转换 X
为int - 它的作用是让浮动的实际的位的 X
,这是通常重新psented如超出你的想象完全是另外一个4字节的值$ p $。
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.
有关参考,这样做,这是一个非常糟糕的主意,除非你知道浮点值究竟是如何重新在内存psented $ P $。
For reference, doing this is a really bad idea unless you know exactly how float values are represented in memory.
这篇关于什么是该C成语是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!