Creating Binary Block from struct

Posted by MOnsDaR on Stack Overflow See other posts from Stack Overflow or by MOnsDaR
Published on 2010-06-16T12:49:08Z Indexed on 2010/06/16 12:52 UTC
Read the original article Hit count: 194

Filed under:
|
|
|

I hope the title is describing the problem, i'll change it if anyone has a better idea.

I'm storing information in a struct like this:

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?
    }
}

The struct should be sent via network in a binary byte-buffer with the following structure:

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

According to this definition the resulting std::vector should have a size of 13 bytes (char == byte)

My question now is how I can form such a packet out of the different datatypes I've got. I've already read through a lot of pages and found datatypes like std::bitset or boost::dynamic_bitset, but neither seems to solve my problem.

I think it is easy to see, that the above code is just an example, the original standard is far more complex and contains more different datatypes. Solving the above example should solve my problems with the complex structures too i think.

One last point: The problem should be solved just by using standard, portable language-features of C++ like STL or Boost (

© Stack Overflow or respective owner

Related posts about c++

Related posts about stl