Convert structure to bytes

How would you convert any structure to an array of bytes on processors with little-endian?

+6
c ++
source share
6 answers

You can use char* to access any type of object in C ++, therefore:

 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 discussion on the correctness of reinterpret_cast compared to static_cast , in practice this does not really matter - both should give the same result)

+11
source share
 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; 
+5
source share
 (char*)&someStruct 
+2
source share

What are you trying to do? If you are trying to serialize a structure in order to save it to a file or pass it in a message, you are better off using a tool designed for this, like pushing :: serialization .

If you just want an array of bytes, you could reinterpret_cast<char*> , as others have mentioned, or do:

 MyStruct s; char [] buffer = new char[sizeof(s)]; memcpy(&buffer, &s, sizeof(s)); 
+2
source share

I would look at void* .

 struct gizmo { //w/e }; //stuff gizmo *G = new gizmo; void* bytearray = (void*)G; 

How your assembly is packaged ambiguously and depends on the compiler, ABI and CPU. You will have to understand this from your manuals and some assemblies.

+1
source share

The problem with all of these answers is that you really cannot do silent byte exchanges without knowing about the data you are exchanging. Character data does not swap. For 64-bit integers, a different type of swap is required depending on how exactly the two processors in question implemented them.

0
source share

All Articles