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.
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.