gpt4 book ai didi

c - 了解快速平方根反比中的指针语法

转载 作者:太空宇宙 更新时间:2023-11-04 06:53:02 27 4
gpt4 key购买 nike

我有一个问题不是关于算法,而是关于快速平方根的语法:

float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;

x2 = number * 0.5F;
y = number;
i = * ( long * ) &y; // evil floating point bit level hacking
i = 0x5f3759df - ( i >> 1 ); // what the...?
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed

return y;
}

我看不懂台词

i = * (long * ) &y;
y = * (float * ) &i;

我知道“&y”是y的内存地址,但我不知道“(long *)”是什么意思,也不知道开头的星号是干什么的。

最佳答案

(long * ) 是一个强制转换,它基本上是在告诉编译器嘿,处理这个浮点指针,就好像它是一个长指针一样

开头的*是一元运算符,用于解引用指针。解引用意味着通过指针访问内存:

int a = 10;
int *p = &a;

printf("%d\n", *p);

将打印 10。这与执行 p[0] 相同。

所以

i = * (long * ) &y;

基本上是在做:将 y 视为指向 long 的指针并保存i 中的 y 指向的值。

这样做是将 float 值的内部位模式复制到 i。现在 i 将有一个基于该位模式的值。

y = * (float * ) &i;

这会做同样的事情,但这次使用的是 i 的值。

这段代码的作用是通过long 修改float 位模式。这代码甚至在注释中有 //evil floating point bit level hacking。我无法告诉您这是如何工作的,因为我不知道快速平方根反比算法。

关于c - 了解快速平方根反比中的指针语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48493553/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com