Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert bitset to array of bytes/uint8?

Tags:

c++

arrays

bitset

I need to extact bytes from the bitset which may (not) contain a multiple of CHAR_BIT bits. I now how many of the bits in the bitset I need to put into an array. For example,

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

There is a separate variable nBits how many of the bits in id are usable. Now I want to extract those bits in multiples of CHAR_BIT. I also need to take care of cases where nBits % CHAR_BIT != 0. I am okay to put this into an array of uint8

like image 333
dubnde Avatar asked Nov 28 '11 15:11

dubnde


People also ask

What is BitSet size?

The default size of the bit set is 64-bit space. If the bit is set at index larger than the current BitSet size, it increases its bit space in the multiplication of 64*n, where n starts from 1, 2, 3, so on.

What does the BitSet function do?

Introduction. Bitset represents a fixed-size sequence of N bits and stores values either 0 or 1. Zero means value is false or bit is unset and one means value is true or bit is set. Bitset class emulates space efficient array of boolean values, where each element occupies only one bit.

How much memory does BitSet use?

Memory Footprint As shown above, this boolean[] consumes around 10 KB of memory. As expected, the BitSet with the same number of bits consumes around 1 KB, which is far less than the boolean[].

How is BitSet implemented in C++?

Let's implement bitset in C++, such that following operations can be performed in stated time complexities : init(int size): initializes a bitset of size number of 0 bits. void fix(int pos): Change the bit at position pos to 1.


2 Answers

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));
}
like image 186
Emile Cormier Avatar answered Sep 30 '22 08:09

Emile Cormier


Unfortunately there's no good way within the language, assuming you need for than the number of bits in an unsigned long (in which case you could use to_ulong). You'll have to iterate over all the bits and generate the array of bytes yourself.

like image 35
Mark B Avatar answered Sep 30 '22 06:09

Mark B