gpt4 book ai didi

C 按位逻辑运算难题

转载 作者:太空宇宙 更新时间:2023-11-04 00:08:11 31 4
gpt4 key购买 nike

所以我需要写一个方法来完成这个谜题:

float_f2i

  • 返回浮点参数 f 的表达式 (int) f 的位级等价物。

  • 参数作为 unsigned int 传递,但它被解释为位级 单精度浮点值的表示。

  • 任何超出范围的值(包括 NaN 和无穷大)都应返回 0x80000000u。

所以我从中得到的是,我得到了一个十六进制数字,我必须编写代码以将其放入整数格式。给我们的测试用例是;参数 [0x00800000],返回 [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;
}

最佳答案

c 只有一个右移运算符 >>> 但当数字是有符号值类型时,这只是算术移位。

main()
{
int x = -2;
printf("%d\n",x>>1);
printf("%d\n",((unsigned int)x)>>1);
return 0;
}

Run it here

因此,如果您需要确保非算术移位,您可以强制转换为 unsigned。

关于C 按位逻辑运算难题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14846565/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com