Fast bitset append?

2019-05-26 16:44发布

I'm looking for a bitset implementation with fast bit appending, where several bits can be efficiently appended in one go.

e.g.

char value = 31;
char n_bits = 5;
fast_bitset bits;
bits.append(value, n_bits);

I have so far tried boost::dynamic_bitset and std::vector. Both of which are slow.


Old Post

I'm using boost::dynamic_bitset to pack some data.

Usually I want to pack ~5 bits at a time which would result in a call like:

char value = 31;
char n_bits = 5;
boost::dynamic_bitset<> bits;
for(char n = n_bits-1; n >= 0; --n)
    bits.push_back((value >> n) & 1);

However this seems to me quite inefficient, couldn't one add all the bits in one go?

e.g.

char value = 31;
char n_bits = 5;
boost::dynamic_bitset<> bits;
bits.append(value, n_bits);

I would expect it to do something like:

template<typename T>
void append(T value, size_t n_bits)
{
     value <<= sizeof(T) - n_bits; // Make target bits most significant, remove all non-target bits.

     // TODO: Shift bits into proper place and use OR to add all target bits to bitset in one go
}

Why doesn't dynamic_bitset have such a function? Would it be possible to implement efficiently?

1条回答
祖国的老花朵
2楼-- · 2019-05-26 17:20

Use the resize member function.

/* Append the lower-order nbits bits from value to set. */
template <typename T>
void append(boost::dynamic_bitset<> &set, T value, size_t nbits)
{
    set.resize(set.size() + nbits);
    for (size_t i=1; i<=nbits; i++) {
        set[set.size() - i] = value & 1;
        value >>= 1;
    }
}
查看更多
登录 后发表回答