将双精度数转换为整数尾数和指数

Fai*_*alM 3 c++ floating-point asn.1

我正在尝试从双精度数中提取尾数和指数部分。对于测试数据“0.15625”,预期尾数和指数分别为“5”和“-5”(5*2^-5)。

double value = 0.15625; 
double mantissa  = frexp(value, &exp);
Run Code Online (Sandbox Code Playgroud)

Result: mantissa = 0.625 and exp = -2

这里返回的尾数是分数。对于我的用例(ASN.1 编码),尾数应该是整数。据我所知,通过右移尾数并调整指数,我可以将二进制分数转换为整数。例如,0.625 base 10is 0.101 base 2、 so3字节被移位以获得整数。但我发现很难找到通用算法。

所以我的问题是,如何计算将十进制小数转换为二进制整数所需移位的位数?

Eri*_*hil 5

#include <cmath>        //  For frexp.
#include <iomanip>      //  For fixed and setprecision.
#include <iostream>     //  For cout.
#include <limits>       //  For properties of floating-point format.


int main(void)
{
    double value = 0.15625;

    //  Separate value into significand in [.5, 1) and exponent.
    int exponent;
    double significand = std::frexp(value, &exponent);

    //  Scale significand by number of digits in it, to produce an integer.
    significand = scalb(significand, std::numeric_limits<double>::digits);

    //  Adjust exponent to compensate for scaling.
    exponent -= std::numeric_limits<double>::digits;

    //  Set stream to print significand in full.
    std::cout << std::fixed << std::setprecision(0);

    //  Output triple with significand, base, and exponent.
    std::cout << "(" << significand << ", "
        << std::numeric_limits<double>::radix << ", " << exponent << ")\n";
}
Run Code Online (Sandbox Code Playgroud)

示例输出:

(5629499534213120, 2, -55)

(如果该值为零,出于美观原因,您可能希望将指数强制为零。从数学上讲,任何指数都是正确的。)