Too convert a struct to an array of bytes ...
Simple assigned via a union. The members of foo will be copied with the assignment, perhaps any padding too. @Eric Postpischil
struct foo {
int x;
float y;
} typedef foo;
foo data_as_foo;
union x_foo {
foo bar;
unsigned char array_o_bytes[sizeof foo];
} x;
x.bar = data_as_foo;
// Do something with x.array_o_bytes
for (unsigned i = 0; i < sizeof x.array_o_bytes; i++) {
printf("%2X ", x.array_o_bytes[i]);
}
An assignment is not even needed.
union x_foo = { .bar = data_as_foo );
What is important about return trip for bytes without alignment to foo is to use memcpy().
foo bytes_to_foo(const unsigned char *data) {
foo y;
memcpy(&y, data, sizeof y);
return y;
}
If the bytes are aligned, as a member of union x_foo, than an assignment is sufficient.
union x_foo data_as_bytes;
// data_as_bytes.array_o_bytes populated somehow
foo data_as_foo = x_foo data_as_bytes.bar;
charas a structure, for which the behavior is not defined by the C standard.