CSAPP实验:unsigned floatPower2(int x)的分析

/* 
 * floatPower2 - Return bit-level equivalent of the expression 2.0^x
 *   (2.0 raised to the power x) for any 32-bit integer x.
 *
 *   The unsigned value that is returned should have the identical bit
 *   representation as the single-precision floating-point number 2.0^x.
 *   If the result is too small to be represented as a denorm, return
 *   0. If too large, return +INF.
 * 
 *   Legal ops: Any integer/unsigned operations incl. ||, &&. Also if, while 
 *   Max ops: 30 
 *   Rating: 4
 * 
 * 计算浮点数2.0^x,结果仍以浮点数的形式存储:
 * 将浮点数表示为十进制的方法为:(-1)^s(1.fraction)2^(exp-127)
 * 本题计算2.0^x,所以s=0,(1.fraction)=0,上式也就简化为2^(exp-127)
 */
unsigned floatPower2(int x)
{
  int exp=x+127;//得到exp的值,也就是阶码部分
  if(exp<0)
    return 0;  //值太小就返回0
  if(exp>255)
    return 0x7f800000;  //值太大就返回+inf
 //结果在合理范围内进行下方操作:
 exp+=127;
  return exp<<23;   //左移23位就得到阶码部分的值,该值表示右移的次数,也即2.0^x
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值