How would you convert any struct into byte array on processors with little-endian?
I like to use a union
:
typedef struct b {
unsigned int x;
unsigned int y;
} b_s;
typedef union a {
b_s my_struct;
char ary[sizeof(b_s)];
} a_u;
You can use a char*
to access any type of object in C++, so:
struct S
{
int a;
int b;
// etc.
};
S my_s;
char* my_s_bytes = reinterpret_cast<char*>(&my_s);
// or, if you prefer static_cast:
char* my_s_bytes = static_cast<char*>(static_cast<void*>(&my_s));
(There is at least some debate over the correctness of the reinterpret_cast
vs. the static_cast
; in practice it doesn't really matter--both should yield the same result)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With