Search code examples
c++socketsserializationboostboost-dynamic-bitset

How does boost::dynamic_bitset store bits


I am having a hard time understanding what boost:::dynamic_bitset, or std::vector do internally. What I eventually want to do is compose a network frame and send it via socket, but I just cannot convert them in a way that keeps the bit order I assembled...

#include <iostream>
#include<stdio.h>
#include "boost/dynamic_bitset.hpp"


int main()
{
    boost::dynamic_bitset<> b(8, 10);          // 8 Bits, value 10

    std::cout << "b     = " << b << std::endl; // as expected

    printf("Vector size: %i\n", b.size());
    printf("Bits: %d", b);                     // ?
    return 0;
}

I understand that the class overloaded the << stream operator, therefore I have correct output, while printf seems to show the raw structure. Appears not even deterministic to me (below repeatedly executed the same .exe without recompiling):

cmd

My questions:

  1. What happens basically under the hood? Apparently it is not at all comparable to an array.
  2. How can I send such a bitset via socket send() ?

Solution

  • boost::dynamic_bitset<> internally stores bits in unsigned integers, which are stored in a std::vector<>. The internal storage is not exposed though, so you cannot access it directly.

    You can use to_block_range to copy a boost::dynamic_bitset<> into an array of integers. And a constructor to convert that array of integers back to a boost::dynamic_bitset<>.