开发者

Convert struct into bytes

开发者 https://www.devze.com 2022-12-28 07:57 出处:网络
How would you co开发者_开发问答nvert any struct into byte array on processors with little-endian?You can use a char* to access any type of object in C++, so:

How would you co开发者_开发问答nvert any struct into byte array on processors with little-endian?


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)


(char*)&someStruct


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;


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));


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消