0

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
  • A function can return a struct or union. Commented Aug 6, 2015 at 19:23

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.