How to convert bits to byte array / uint8?

I need to derive bytes from a bit set that may (not) contain multiple bits of CHAR_BIT. I now how many bits in a bitet I need to insert into an array. For instance,

set of bits declared as std::bitset < 40> id;

There is a separate variable nBitshow many bits idcan be used. Now I want to extract these bits in a few CHAR_BIT. I also need to take care of cases when nBits % CHAR_BIT != 0. I can put this in a uint8 array

+5
source share
2 answers

Unfortunately, there is no good way in the language if you need more than the number of bits in unsigned long(in this case, you could use to_ulong). You will have to iterate over all the bits and generate an array of bytes yourself.

+3
source

You can use boost :: dynamic_bitset , which can be converted to a range of "blocks" using boost :: to_block_range .

#include <cstdlib>
#include <cstdint>
#include <iterator>
#include <vector>
#include <boost/dynamic_bitset.hpp>

int main()
{
    typedef uint8_t Block; // Make the block size one byte
    typedef boost::dynamic_bitset<Block> Bitset;

    Bitset bitset(40); // 40 bits

    // Assign random bits
    for (int i=0; i<40; ++i)
    {
        bitset[i] = std::rand() % 2;
    }

    // Copy bytes to buffer
    std::vector<Block> bytes;
    boost::to_block_range(bitset, std::back_inserter(bytes));
}
+15
source

All Articles