简体   繁体   English

将单精度浮点数乘以2

[英]Multiplying single precision float with 2

This is a homework question. 这是一个家庭作业问题。 I already found a lot of code online, including some code in StackOverflow. 我已经在网上找到了很多代码,包括StackOverflow中的一些代码。 But I just want the concept not the code. 但我只想要概念而不是代码。 I want to implement it myself. 我想自己实现它。 So the function I want to implement is: 所以我想实现的功能是:

  • float_twice - Return bit-level equivalent of expression 2*f for floating point argument f . float_twice - 返回浮点数参数f的表达式2*f位级等价物。
  • Both the argument and result are passed as unsigned int 's, but they are to be interpreted as the bit-level representation of single-precision floating point values. 参数和结果都作为unsigned int传递,但它们将被解释为单精度浮点值的位级表示。

I want to know how to do this. 我想知道怎么做。 I know floating point representation. 我知道浮点表示法。 And read wiki page on how to multiply two floats, but didn't understand it. 并阅读有关如何乘以两个浮点数的维基页面,但不理解它。 I just want to know the concept/algorithm for it. 我只是想知道它的概念/算法。

Edit: 编辑:

Thanks everyone. 感谢大家。 Based on your suggestions I wrote the following code: 根据您的建议,我写了以下代码:

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

You could do something like this (although some would claim that it breaks strict-aliasing rules): 你可以做这样的事情(尽管有些人声称它违反了严格别名规则):

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));
}

In any case, you'll have to assert that the size of float is equal to the size of int on your platform. 在任何情况下,您都必须声明float的大小等于平台上int的大小。


If you just want to take an unsigned int operand and perform on it the equivalent operation of multiplying a float by 2, then you can simply add 1 to the exponent part of it (located in bits 20-30): 如果你只想取一个unsigned int操作数并在其上执行将float乘以2的等效操作,那么你可以简单地将1加到它的指数部分(位于第20-30位):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM