这个 C 习语是什么意思?

发布于 2024-09-13 22:16:25 字数 589 浏览 3 评论 0原文

可能的重复:
约翰·卡马克的不寻常的快速平方根倒数(雷神之锤 III)

我最近在博客上看到了这段代码 - 它来自 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你对谁都笑 2024-09-20 22:16:25

int i = *(int*)&x; 不会将 x 转换为 int —— 它所做的是获取实际的 的 float x,它通常表示为一个与您预期不同的 4 字节值。

作为参考,这样做是一个非常糟糕的主意,除非您确切地知道浮点值在内存中的表示方式。

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.

℉絮湮 2024-09-20 22:16:25

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)

网名女生简单气质 2024-09-20 22:16:25

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文