【发布时间】:2026-02-06 11:30:01
【问题描述】:
我希望标题描述了这个问题,如果有人有更好的想法,我会改变它。
我将信息存储在这样的结构中:
struct AnyStruct
{
AnyStruct() :
testInt(20),
testDouble(100.01),
testBool1(true),
testBool2(false),
testBool3(true),
testChar('x') {}
int testInt;
double testDouble;
bool testBool1;
bool testBool2;
bool testBool3;
char testChar;
std::vector<char> getBinaryBlock()
{
//how to build that?
}
}
该结构应通过网络以具有以下结构的二进制字节缓冲区发送:
Bit 00- 31: testInt
Bit 32- 61: testDouble most significant portion
Bit 62- 93: testDouble least significant portion
Bit 94: testBool1
Bit 95: testBool2
Bit 96: testBool3
Bit 97-104: testChar
根据此定义,生成的 std::vector 的大小应为 13 个字节(char == byte)
我现在的问题是如何从我拥有的不同数据类型中形成这样的数据包。我已经阅读了很多页面,发现了 std::bitset 或 boost::dynamic_bitset 等数据类型,但似乎都不能解决我的问题。
我认为很容易看出,上面的代码只是一个示例,原始标准要复杂得多,并且包含更多不同的数据类型。我认为解决上面的例子应该也可以解决我对复杂结构的问题。
最后一点: 该问题应该通过使用标准的、可移植的 C++ 语言特性(如 STL 或 Boost)来解决(
【问题讨论】: