所以我需要写一个方法来解决这个难题:
浮动_f2i
返回浮点参数 f 的表达式 (int) f 的位级等效项。
参数作为 unsigned int 传递,但它被解释为单精度浮点值的位级表示。
任何超出范围(包括 NaN 和无穷大)都应返回 0x80000000u。
所以我从中得到的是,我得到了一个十六进制的数字,我必须编写代码把它变成整数格式。给我们的一个测试用例是;
Argument [0x00800000], returns [0x0]
因为 0x00800000 是 1.1754....E-38,小到可以返回为零(所以我假设)
到目前为止,我所拥有的是:
int float_f2i(unsigned uf) {
unsigned sign = uf & (0x80000000);
unsigned exp = uf >> 23 & 0xff;
unsigned frac = uf & 0x7fffff;
//takes care of NaN and inifinity
if (exp == 255) {return 0x80000000u;}
if ((exp > 0) && (exp < 255)) //normalized
{
if ((sign >> 28) == 0x0) //if sign bit is 0
{
return (0x1); //NEEDS MORE HERE
}
else if ((sign >> 28) == 0x8) //if sign bit is 1
{
return (0x8); //NEEDS MORE HERE
}
}
else if (exp == 0)//denormalized
{
return 0; // rounds to zero anyway
}
}
我知道要使它起作用,我必须将指数部分添加到返回语句(1.frac ^(exp-127))中,但我不知道如何对其进行编码。向左移动乘以二,但对于2 的负指数,我需要右移,但 >> 运算符在算术上执行此操作。我是否需要创建一个动态掩码来消除算术移位创建的 1 位?
编辑:得到了答案,我走错了方向,如果有人必须这样做,未来的参考:
int float_f2i(unsigned uf) {
int exponent = (uf >> 23) & 0ff;
int exp = exponent - 127;
int frac = uf & 0x7fffff;
if(exponent == 0x7F800000)
return 0x80000000u;
if(!exponent)
return 0;
if(exp < 0)
return 0;
if(exp > 30)
return 0x80000000u;
frac = frac | 0x800000;
if (exp >= 23)
frac = frac << (exp - 23);
else
frac = frac >> (23 - exp);
if((uf >> 31) & 1)
return ~frac + 1;
return frac;
}