I've got a byte array containing 8 bytes and would like to convert and use them as a double precision binary floating-point number.
Could someone please tell me how to convert it?
I've got a byte array containing 8 bytes and would like to convert and use them as a double precision binary floating-point number.
Could someone please tell me how to convert it?
Try this:
double a;
memcpy(&a, ptr, sizeof(double));
where ptr
is the pointer to your byte array. If you want to avoid copying use a union, e.g.
union {
double d;
char bytes[sizeof(double)];
} u;
// Store your data in u.bytes
// Use floating point number from u.d
Here is one solution using memcpy
function:
double d = 0;
unsigned char buf[sizeof d] = {0};
memcpy(&d, buf, sizeof d);
Note that a solution like:
d = *((double *) buf);
shoud be avoided. This is undefined behavior because it potentially violates alignment and aliasing rules.
In C++:
double x;
char buf[sizeof(double)]; // your data
#include <algorithm>
// ...
std::copy(buf, buf + sizeof(double), reinterpret_cast<char*>(&x));
In C:
#include <string.h>
/* ... */
memcpy(&x, buf, sizeof(double));
In C++11, you can also use std::begin(buf)
and std::end(buf)
as the boundaries (include the header <iterator>
), and in both languages you can use sizeof(buf) / sizeof(buf[0])
(or simply sizeof(buf)
) for the size, all provided buf
is actually an array and not just a pointer.