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.

Share:
29,283
beta
Author by

beta

Forever trust in who we are

Updated on July 09, 2022

Comments

  • beta
    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
    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
    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
    unwind over 12 years
    Shouldn't that be sizeof a? :)
  • Martin York
    Martin York over 12 years
    First time I have seen sizeof d rather than sizeof(d)
  • ouah
    ouah over 12 years
    @LokiAstari sizeof is an operator and not a function. This the C syntax of sizeof when the operand is an expression. The parentheses are unneccesary. But they are required by the synatx if you use sizeof with a type name operand.
  • Martin York
    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
    M.M over 9 years
    This question is tagged both C and C++. In C the union version works, in C++ it causes undefined behaviour.
  • simplename
    simplename over 2 years
    What is the type of (double *) buf? I have never seen a cast from uint8_t * to double * like this. Can it be static_cast? reinterpret_cast? Would those work (aside from the alignment/aliasing)