Dylan Meiners
Dylan Meiners

Reputation: 51

How do I convert an unsigned char buffer to a double in C++?

I am trying to convert an unsigned char buffer array into a double. Why does this not copy the bytes into the double as they are in the array?

#include <iostream>
#include <string>

int main() {

    unsigned char buffer[8] = {63, 240, 0, 0, 0, 0, 0, 0};
    double x = *(double*)buffer;
    std::cout << x << std::endl;
    return 0;
}

I also tried doing this:

#include <iostream>
#include <string>

int main() {

    unsigned char buffer[8] = {63, 240, 0, 0, 0, 0, 0, 0};
    double x ;
    memcpy(&x, buffer, sizeof(double)); //NOW USING MEMCPY
    std::cout << x << std::endl;
    return 0;
}

I looked at this post here, but it only got the same results. The unsigned chars {63, 240, 0, 0, 0, 0, 0, 0} is the representation of the double number 1.

It outputs: 3.03865e-319.

Upvotes: 0

Views: 816

Answers (1)

catnip
catnip

Reputation: 25388

You've got your buffer round the wrong way. It should be:

{0, 0, 0, 0, 0, 0, 240, 63}

(on a little-endian machine using IEEE floating point).

Live demo

Upvotes: 1

Related Questions