I am writing a program in c that runs on 32-bit Microcontroller. I have a double and I want to transform it into an array of bytes. These bytes will be later sent to another microcontroller. But I do not know which method I should use to perform this task. Any Suggestion? The Problem consists in the inability in c to define a function that returns an array. So I must define an array outside the function and then process it inside the c-function which does not satisfy my needs
1 Answer
You can use type-punning through a union:
union{
double d;
unsigned char bytes[sizeof(double)];
} d2b;
d2b.d = 3.14;
You can access the bytes through d2b.bytes. Note that this assumes both micro-controllers use the same (internal) representation for doubles. If not, use some sort of serialization.
Edit:
Seeing your edit. You could also just memcpy and 'return' it through an output-parameter:
unsigned char * doubleToBytes(unsigned char bytes[sizeof(double)], double d){
return memcpy(bytes, &d, sizeof d);
}