How would you convert any struct into byte array on processors with little-endian?
-
2expand upon your request please - and note that your answer will be extremely processor architecture dependentKevinDTimm– KevinDTimm2010-04-22 15:56:07 +00:00Commented Apr 22, 2010 at 15:56
-
What is the addressing unit for little endian? What are you really trying to do?WhirlWind– WhirlWind2010-04-22 16:10:57 +00:00Commented Apr 22, 2010 at 16:10
6 Answers
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)
4 Comments
char* b = (char*)&my_s; Perhaps if i learn C++ again, I'll read something about those cast constructs first.reinterpret_cast in this case, because no combination of static_cast and const_cast is valid. Using the C++ style casts guarantees you get the cast you intend; the C-style cast basically just tries a sequence of five different types of casts until it finds one that works.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;
4 Comments
ary[sizeof(b)]?What are you trying to do? If you're trying to serialize the struct so you can save it to a file or pass it in a message, you're better off using a tool designed for that like boost::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));
Comments
I would peer into the void*.
struct gizmo
{
//w/e
};
//stuff
gizmo *G = new gizmo;
void* bytearray = (void*)G;
How your struct gets packed is ambiguous and depends on compiler, ABI, and CPU. You'll have to figure that out from your manuals & some assembly reading.
2 Comments
The problem with all of these answers is that you can't really do dumb byte swapping without knowing something about the data you are swapping. Character data does not get swapped. 64-bit integers need a different kind of swapping depending on exactly how the two processors in question implemented them.