将双数字的64位二进制字符串表示形式转换回c ++中的双数字

jer*_*ome 7 c++

我有一个双数的IEEE754双精度64位二进制字符串表示.示例:double value = 0.999; 其二进制表示为"0011111111101111111101111100111011011001000101101000011100101011"

我想将此字符串转换回c ++中的双精度数.我不想使用任何外部库或.dll,因为我的程序可以在任何平台上运行.

fre*_*low 10

C字符串解决方案

#include <cstring>   // needed for all three solutions because of memcpy

double bitstring_to_double(const char* p)
{
    unsigned long long x = 0;
    for (; *p; ++p)
    {
        x = (x << 1) + (*p - '0');
    }
    double d;
    memcpy(&d, &x, 8);
    return d;
}
Run Code Online (Sandbox Code Playgroud)

std::string 解:

#include <string>

double bitstring_to_double(const std::string& s)
{
    unsigned long long x = 0;
    for (std::string::const_iterator it = s.begin(); it != s.end(); ++it)
    {
        x = (x << 1) + (*it - '0');
    }
    double d;
    memcpy(&d, &x, 8);
    return d;
}
Run Code Online (Sandbox Code Playgroud)

通用解决方案

template<typename InputIterator>
double bitstring_to_double(InputIterator begin, InputIterator end)
{
    unsigned long long x = 0;
    for (; begin != end; ++begin)
    {
        x = (x << 1) + (*begin - '0');
    }
    double d;
    memcpy(&d, &x, 8);
    return d;
}
Run Code Online (Sandbox Code Playgroud)

示例调用:

#include <iostream>

int main()
{
    const char * p = "0011111111101111111101111100111011011001000101101000011100101011";
    std::cout << bitstring_to_double(p) << '\n';

    std::string s(p);
    std::cout << bitstring_to_double(s) << '\n';

    std::cout << bitstring_to_double(s.begin(), s.end()) << '\n';
    std::cout << bitstring_to_double(p + 0, p + 64) << '\n';
}
Run Code Online (Sandbox Code Playgroud)

注意:我假设unsigned long long有64位.更简洁的解决方案是包含<cstdint>和使用uint64_t,假设您的编译器是最新的并提供C++ 11标头.