语言:C++
我正在研究位打包(从给定数据中提取所需的位并将它们打包在 char* 中)。我的代码目前支持: - 整数 - 字符 - 字符串
现在,如果我必须存储结构所需的位,我应该怎么做?我的意思是我应该期望什么作为通用代码 wrt 结构的输入参数?
这个问题可能含糊不清,我并不期待直接的答案,即使是提示和指针也值得赞赏。
语言:C++
我正在研究位打包(从给定数据中提取所需的位并将它们打包在 char* 中)。我的代码目前支持: - 整数 - 字符 - 字符串
现在,如果我必须存储结构所需的位,我应该怎么做?我的意思是我应该期望什么作为通用代码 wrt 结构的输入参数?
这个问题可能含糊不清,我并不期待直接的答案,即使是提示和指针也值得赞赏。
看看这个非常紧凑的格式或使用标准的编组格式,如 json、xml、boost 序列化......
As piotr already suggested: try using existing libraries to marshall.
However, since your already doing it yourself:
If your supported primitives are representable as bytes, then you shouldn't be bit packing (there might be some confusion about the term), otherwise consider using std::bitset.
Because C++ doesn't support reflection, there is no help in C++ to byte pack structures in a generic, safe and portable way, so be prepared to write a function per structure to pack each primitive and each member structure.
Overloading does help to call these functions in a generic way, so packing of containers (vector ...) can be done generically. However, if you want this, then prefer free functions over member functions, to avoid having a difference between packing primitives and packing structures.
Example:
void Pack(const MyStruct& str, Packer& pack)
{
Pack(str.int1, pack);
Pack(str.string1, pack);
Pack(str.otherStruct, pack);
}
您可以使用reinterpret_cast<char*>()
来访问结构,就好像它是char*
:
#include <iostream>
using namespace std;
struct myStruct
{
char a; int b;
};
int main(int argc, char* argv[])
{
myStruct instance = { 10, 100 };
//Treat the myStruct instance as though it were a char*
char* pchar = reinterpret_cast<char*>(&instance);
//Output the values of the bytes to the console
for(int i = 0; i < sizeof(instance); i++)
cout << (int)pchar[i] << endl;
getchar();
return 0;
}
但是请注意,由于对齐,并非所有字符都包含有意义的数据。这可以修复,至少在 Visual Studio 中,使用pack pragma .. 但结果仍然高度依赖于架构/编译器。
因此,如果您想以一种完全可移植/可维护的方式打包字节(即您将在现实世界中使用它),我强烈建议使用 piotr 提到的序列化方法之一。