Fast bitset append?

大憨熊 提交于 2019-12-22 17:48:28

问题


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:


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;
    }
}


来源:https://stackoverflow.com/questions/5754742/fast-bitset-append

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!