首页 > 开发 > C++ > 正文

float*与int*互转会导致数据不正确,为什么C/C++还允许这么转?有其他什么用途吗?

2017-09-11 21:35:05  来源: 网友分享

float* 与 int* 互转会导致数据不正确,为什么C/C++还允许这么转?有其他什么用途吗?

解决方案

我来举一个最经典的例子吧!http://zh.wikipedia.org/zh/%E5%B9%B3%E6%96%B9%E6%A0%B9%E5%80%92%E6%95%B0%E9%80%9F%E7%AE%97%E6%B3%95

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(对浮点数的邪恶位级hack)    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;}

反正你可以这么做,于是你就可以作出很多超乎想想的事情~

这里通过过吧float*转成long*,将原浮点数的二进制表示直接与某个数相减来实现一个平方根倒数的估计。