Auto resizing the dynamic_bitset

198 Views Asked by At

So I have a vector of numbers, example 4, 20, 1500, 4, 270. The first element will occupy 3 bits, second 5 bits, 3rd 11 bits and so on. How do I set the bit_size to automatically change according to the number of bits the element will occupy? Like,

int bit_size = 4; 
boost::dynamic_bitset<> B(bit_size, 4);
1

There are 1 best solutions below

0
On

If you want to automatically calculate the minimal number of bits your value occupies then you can do something like this:

#include <cmath>
...
int value_to_write = 4;
int min_bits = std::floor(1 + std::log2(value_to_write));
boost::dynamic_bitset<> B(min_bits, value_to_write);

Note, that first argument in dynamic_bitset ctor is the number of bits, not the value.