OpenMask
OpenMask

Reputation: 21

Extract data from uint8 to double

I have a C function receiving a uint8 pointer with another parameter which is its size (number of bytes).

I want to extract double data from this buffer. Here is my code:

Write(uint8* data, uint8 size) /* data and size are given by a callback to my function)*/
{
    double d;
    for (i = 0; i < size; i++)
    {
        d = ((double*)&data)[i];
        printf(" d = %d\n");
    }
}

The problem is that I am not receiving what I am sending within an external hardware. I guess that my cast is wrong. I tried other methods but without any good result. I am still not able to get what I send.

Upvotes: 0

Views: 5313

Answers (3)

Vaughn Cato
Vaughn Cato

Reputation: 64308

Assuming your data is actually an array of doubles and size is the number of bytes, your code should look something like this:

Write(uint8* data, uint8 size) /* data and size are given by a callback to my function)*/
{
  double d;
  int i;
  for (i=0; i<size/sizeof(double); ++i) {
    d = ((double*)data)[i];
    printf(" d = %g\n",d);
  }
}

Most likely, size is the number of bytes and not the number of doubles, so you have to divide size by the size of a double to get the actual number of doubles:

If you do this:

    d = ((double*)&data)[i];

then you are saying that the pointer to the pointer to the data is a double pointer.

Also, your printf statement was like this:

printf(" d = %d\n");

You were telling it to print an int (%d is an int), and not giving it an actual value to print. I changed that to %g, which prints a double in best-fit format.

Upvotes: 2

Alexey Frunze
Alexey Frunze

Reputation: 62106

If I understand your question (it's not entirely clear if there's at most one double to extract or there can be many), here's what I would try doing:

double Write(uint8* data, uint8 size)
{
    double d;

    if (size < sizeof(d))
        return 0; // failure; you may want something smarter than this

    memcpy(&d, data, sizeof(d));

    return d;
}

What this avoids is a potential alignment issue in a cast like d = *(double*)data.

This may fail in odd and ugly ways if the data does not represent a valid double, specifically if it's reversed (e.g. your hardware is little-endian and the CPU running this code is big-endian or the other way around).

I don't know yet if aliasing issues apply. Need to read the standard again. Never saw them in practice, though.

Upvotes: 0

DanZimm
DanZimm

Reputation: 2578

Write(uint8* data, uint8 size) /* data and size are given by a callback to my function)*/
 {

  double d;
  for (i=0; i<size; i++) {
  d = ((double*)data)[i];
  printf(" d = %d\n", d);
  }

 }

is what im guessing you're looking for, the pointer is actually a pointer to an array of doubles so you just cast it to exactly that

Upvotes: 1

Related Questions