0
votes

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.

1
You forgot about endianness. - eesiraed
How did you arrive at the conclusion that these values are, indeed, the value 1? Did you try compiling double d=1; with optimization turned off, and dump the contents of this variable, in hex? - Sam Varshavchik
I used an online double to binary converter. I also tried the hex version. - Dylan Meiners
It was because I had the numbers in big-endian style, not little-endian style. - Dylan Meiners

1 Answers

1
votes

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