简体   繁体   中英

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM