c++ - Convert 8 bytes to double value -


this question has answer here:

i read socket hex data. specification protocol tells me following 8 bytes represent double value.

so have example 8 byte like:

0x3f 0xd1 0x9b 0x94 0xc0 0x00 0x00 0x00 

(this value saved in char array array[0] = 0x3f, `array[1] = 0xd1รจ...)

the represented double value is: 0.275120913982

how can convert these 8 bytes double value?

i tried lot of different things, nothing works really. have no idea how can manipulate double.

you can use union, works me:

#include <iostream> using namespace std;  int main() {     union { char b[8]; double d; };     b[7] = 0x3f;     b[6] = 0xd1;     b[5] = 0x9b;     b[4] = 0x94;     b[3] = 0xc0;     b[2] = 0x00;     b[1] = 0x00;     b[0] = 0x00;      cout << "double: " << d << endl;      return 0; } 

please note reverse order of bytes. depends on endianness , can differ on machine. anyway outputs:

double: 0.275121 

Comments