C++ code to verify IEEE 754 double precision floating-point format

As the title says, let the code talk.

//feel free to use it in your project with nothing guaranteed
//mail to: bruceadi(at)hotmail.com 
//to verity Double-precision floating-point format, see the link http://en.wikipedia.org/wiki/Double_precision
#include <iostream> 
#include <limits> 
class Double
{
public:
  explicit Double(double v)
  {
    /*1, 11, 52*/    
    sign = (*(unsigned __int64*)(&v) >> 63) ? -1: 1;
    unsigned __int64 t = exp = (*(unsigned __int64*)(&v) >> 52) & 0x7ff; 
    if(0 != t && t != 0x7ff)
    {
      exp =(int)(t - 1023);
    }
    man = *(unsigned __int64*)(&v) << 12;
  }

  operator double() const
  {
    if(!exp)
    {
      return 0;
    }
    else if(0x7ff == exp)
    {
      return !man ? std::numeric_limits<double>::infinity()  : 
         std::numeric_limits<double>::quiet_NaN();
    }

    double e = exp;
    double final = 1.0;
    unsigned __int64 m = man;
    while( e < 0)
    {
      final *= 0.5;
      ++e;
    }
    while(e > 0)
    {
      final *= 2.0;
      --e;
    }
    double prec = final;
    while(m)
    {
      prec *= 0.5;
      if(m >> 63)
      {
        final += prec;
      }
      m <<= 1;
    }
    return final;
  }
private:
  int exp;
  char sign;
  unsigned __int64 man;
};

int main ()
{
  double f[5];
  f[0] = 1.0/3;
  f[1] =  std::numeric_limits<double>::quiet_NaN();
  f[2] =  std::numeric_limits<double>::infinity();
  f[3] = 1e-20;
  f[4] = 0.0;
  for(size_t i = 0; i < 5; ++i)
  {
    std::cout << f[i] << " : " << (double)(Double(f[i])) << std::endl;
  }
  return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值