c++ - '*(<type> *) &x' 和 'x' 有什么区别?

标签 c++ pointers casting memory-address

有什么区别

int i = 123;
int k;
k = *(int *) &i;
cout << k << endl; //Output: 123

int i = 123;
int k;
k = i;
cout << k << endl; //Output: 123

它们都给出相同的输出,但有什么不同吗?

(我在快速平方根反函数的 Quake3 代码中找到了第一个片段)

最佳答案

第三季度:

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 fuck?
    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 是一个floati 是一个long。因此,它是将浮点位模式重新解释为整数位模式。

关于c++ - '*(<type> *) &x' 和 'x' 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16645233/

相关文章:

java - 来自 java 源的工件提取器

c - 如何将字符指针传递给函数

pointers - 如何在不明确指定该字段的情况下打印字段的取消引用值golang

php - 谁能解释为什么 strtotime ('cast' ) 返回一个值?

c++ - 如何使用 Windows native Wifi 功能连接到请求网络安全 key 的 Wifi?

c++ - 在构造函数 C++ 中创建指向对象的指针

c++ - 指针向下转换和向上转换的用法区别?

c - 带有类型转换的讨厌的指针数组,Invalid Initializer 错误

c# - 基类数组到派生类数组的转换

c++ - 如何保存用户的整数输入,并返回一个字符串值?