Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert 64-bit binary string representation of a double number back to double number in c++

Tags:

c++

I have a IEEE754 Double precision 64-bit binary string representation of a double number. example : double value = 0.999; Its binary representation is "0011111111101111111101111100111011011001000101101000011100101011"

I want to convert this string back to a double number in c++. I dont want to use any external libraries or .dll's as my program would operate in any platform.

like image 791
jero2rome Avatar asked Dec 23 '11 13:12

jero2rome


2 Answers

C string solution:

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

std::string solution:

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

generic solution:

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

example calls:

#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';
}

Note: I assume unsigned long long has 64 bits. A cleaner solution would be to include <cstdint> and use uint64_t instead, assuming your compiler is up to date and provides that C++11 header.

like image 160
fredoverflow Avatar answered Dec 04 '22 09:12

fredoverflow


A starting point would be to iterate through the individual characters in the string and set individual bits of an existing double.

like image 40
Luchian Grigore Avatar answered Dec 04 '22 08:12

Luchian Grigore