How to convert a byte array into double in C?
29,283
Solution 1
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
Solution 2
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.
Solution 3
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.
Comments
-
beta almost 2 years
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?
-
R.. GitHub STOP HELPING ICE over 12 years+1 for pointing out that the typical approach is unsafe and invokes UB for two reasons.
-
Kerrek SB over 12 years@R.: actually there's only one reason (namely "because the standard says so"), but indeed it is good to know the actual pitfalls which reckless casting can cause.
-
unwind over 12 yearsShouldn't that be
sizeof a
? :) -
Martin York over 12 yearsFirst time I have seen
sizeof d
rather thansizeof(d)
-
ouah over 12 years@LokiAstari
sizeof
is an operator and not a function. This the C syntax ofsizeof
when the operand is an expression. The parentheses are unneccesary. But they are required by the synatx if you usesizeof
with a type name operand. -
Martin York over 12 years@ouah: I was aware that you could do it. I had just not seen it before. The worst part now is that I have to debate with myself which is clearer so that I can have a good usage and be consistent. Ba humbug my brain is too old and fixed for multiple choices.
-
M.M over 9 yearsThis question is tagged both C and C++. In C the union version works, in C++ it causes undefined behaviour.
-
simplename over 2 yearsWhat is the type of
(double *) buf
? I have never seen a cast fromuint8_t *
todouble *
like this. Can it be static_cast? reinterpret_cast? Would those work (aside from the alignment/aliasing)