C++ 将结构体转换为字节

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2692383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:22:20  来源:igfitidea点击:

Convert struct into bytes

c++

提问by cpx

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

您将如何在具有小端序的处理器上将任何结构转换为字节数组?

回答by James McNellis

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

您可以使用 achar*访问 C++ 中的任何类型的对象,因此:

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 debateover the correctness of the reinterpret_castvs. the static_cast; in practice it doesn't really matter--both should yield the same result)

(至少有一些争论过的正确性reinterpret_cast主场迎战static_cast;实际上它并没有真正的问题-两者都应该产生相同的结果)

回答by WhirlWind

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;

回答by Andrey

(char*)&someStruct

回答by David

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.

你想做什么?如果您尝试序列化结构以便将其保存到文件或在消息中传递它,则最好使用专为此设计的工具,例如boost::serialization

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

如果你只想要一个字节数组,你可以reinterpret_cast<char*>像其他人提到的那样,或者做:

MyStruct s;
char [] buffer = new char[sizeof(s)];
memcpy(&buffer, &s, sizeof(s));

回答by Paul Nathan

I would peer into the void*.

我会凝视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.

您的结构如何打包是不明确的,取决于编译器、ABI 和 CPU。你必须从你的手册和一些汇编阅读中弄清楚这一点。

回答by T.E.D.

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 notget swapped. 64-bit integers need a different kind of swapping depending on exactly how the two processors in question implemented them.

所有这些答案的问题在于,在不了解要交换的数据的情况下,您无法真正进行愚蠢的字节交换。字符数据也不会被换。64 位整数需要不同类型的交换,具体取决于所讨论的两个处理器如何实现它们。