gpt4 book ai didi

c++ - 将 float 类型转换为 int 的正确方法是什么,反之亦然?

转载 作者:IT老高 更新时间:2023-10-28 13:02:39 33 4
gpt4 key购买 nike

下面的代码通过一些位黑客来执行快速的平方根逆运算。该算法可能是由 Silicon Graphics 在 1990 年代早期开发的,它也出现在 Quake 3 中。 more info

但是,我从 GCC C++ 编译器得到以下 警告:取消引用类型双关指针会破坏 严格别名 规则

在这种情况下我应该使用 static_castreinterpret_cast 还是 dynamic_cast

float InverseSquareRoot(float x)
{
float xhalf = 0.5f*x;
int32_t i = *(int32_t*)&x;
i = 0x5f3759df - (i>>1);
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x);
return x;
}

最佳答案

忘记类型转换。使用 memcpy

float xhalf = 0.5f*x;
uint32_t i;
assert(sizeof(x) == sizeof(i));
std::memcpy(&i, &x, sizeof(i));
i = 0x5f375a86 - (i>>1);
std::memcpy(&x, &i, sizeof(i));
x = x*(1.5f - xhalf*x*x);
return x;

原始代码尝试通过首先通过 int32_t 指针访问 float 对象来初始化 int32_t,这是违反规则的地方. C 风格的转换等效于 reinterpret_cast,因此将其更改为 reinterpret_cast 不会有太大区别。

使用 memcpy 的重要区别是字节从 float 复制到 int32_t 中,但永远不会访问 float 对象通过 int32_t 左值,因为 memcpy 采用指向 void 的指针,并且它的内部是“神奇的”并且不会破坏别名规则。

关于c++ - 将 float 类型转换为 int 的正确方法是什么,反之亦然?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17789928/

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