c - 单精度 float 乘以 2

标签 c floating-point bit-manipulation

这是一个家庭作业问题。我已经在网上找到了很多代码,包括StackOverflow中的一些代码。但我只想要概念而不是代码。我想自己实现。所以我要实现的功能是:

  • float_twice - 返回浮点参数 f 的表达式 2*f 的位级等效项。
  • 参数和结果都作为无符号整数传递,但它们将被解释为单精度浮点值的位级表示。

我想知道如何做到这一点。我知道浮点表示。并阅读了有关如何将两个 float 相乘的维基页面,但不明白。我只是想知道它的概念/算法。

编辑:

谢谢大家。根据您的建议我编写了以下代码:

unsigned float_twice(unsigned uf) {
    int s = (uf >> 31) << 31;
    int e = ((uf >> 23) & 0xFF) << 23;
    int f = uf & 0x7FFF;

    // if exponent is all 1's then its a special value NaN/infinity
    if (e == 0xFF000000){
        return uf;
        
    } else if (e > 0){  //if exponent is bigger than zero(not all zeros', not al 1's, 
                        // then its in normal form, add a number to the exponent
        return uf + (1 << 23);
        
    } else { // if not exponent not all 1's and not bigger than zero, then its all 
             // 0's, meaning denormalized form, and we have to add one to fraction

        return uf +1;
    } //end of if
    
} //end of function

最佳答案

你可以这样做(尽管有些人会声称它违反了严格别名规则):

unsigned int func(unsigned int n)
{
    float x = *(float*)&n;
    x *= 2;
    return *(unsigned int*)&x;
}

void test(float x)
{
    unsigned int n = *(unsigned int*)&x;
    printf("%08X\n",func(n));
}

无论如何,您都必须断言您平台上 float 的大小等于 int 的大小。

<小时/>

如果您只想获取一个 unsigned int 操作数并对其执行与 float 乘以 2 的等效运算,那么您只需在指数上加 1其部分内容(位于第 20-30 位):

unsigned int func(unsigned int n)
{
    return n+(1<<20);
}

关于c - 单精度 float 乘以 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25938221/

相关文章:

c - 哈希函数给我极大的数字

c - 如何用 C 语言读取和编辑 .txt 文件?

floating-point - "epsilon"真的能保证浮点计算中的任何东西吗?

c++ - 如果第一位小数大于或等于5,如何+1到数字?

c - 为什么输出为负(使用按位非)

ios - 需要帮助了解 << 位运算符在 Objective-C 中的工作原理

python - python中等效的C/C++ losose算法是什么

c - qsort 比较函数行为

带浮点变量的 C++ 递归函数

c - 使用位算术从二进制 int 获取绝对值