/*
* 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
}
CSAPP实验:unsigned floatPower2(int x)的分析
最新推荐文章于 2023-11-01 00:10:41 发布