这个 C 习语是什么意思?
我最近在博客上看到了这段代码 - 它来自 Quake3 引擎。它的目的是使用牛顿-拉普森方法快速计算平方根倒数。
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;
会得到完全不同的结果。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
int i = *(int*)&x;
不会将x
转换为 int —— 它所做的是获取实际的位 的 floatx
,它通常表示为一个与您预期不同的 4 字节值。作为参考,这样做是一个非常糟糕的主意,除非您确切地知道浮点值在内存中的表示方式。
int i = *(int*)&x;
doesn't convertx
to an int -- what it does is get the actual bits of the floatx
, 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.
int i = *(int*)&x;
表示“获取构成浮点值 x 的四个字节,并将它们视为 int”。 float 值和 int 值使用完全不同的方法存储(例如 int 4 和 float 4.0 具有完全不同的位模式)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)以
i
结尾的数字是 IEEE< 的二进制值/a> x 中数字的浮点表示。该链接解释了它的样子。这不是常见的 C 习惯用法,这是在 SSE 指令添加到商用 x86 处理器之前的一个聪明技巧。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.