Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert struct into bytes

Tags:

c++

How would you convert any struct into byte array on processors with little-endian?

like image 484
cpx Avatar asked Apr 22 '10 15:04

cpx


2 Answers

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;
like image 78
WhirlWind Avatar answered Oct 10 '22 02:10

WhirlWind


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)

like image 33
James McNellis Avatar answered Oct 10 '22 01:10

James McNellis