Boost dynamic_bitset - put an integer value into a range of bits

泄露秘密 提交于 2019-12-11 01:46:37

问题


I have a 7-byte/56-bit bitset that upon construction sets the first bit to one:

boost::dynamic_bitset<> b(56, 1);

After construction, I'd like to place an integer value (say 2019) into bits 4 through 15. I'm curious if there is a simple way within boost to do this without bitwise operations? Basically, I want to set a range of bits to an integer value that I know is small enough to fit into those bits. Thanks for any advice.


回答1:


The boost::dynamic_bitset<> offers much less functionality. I think the only possibility is to use an ordinary loop:

template <typename Bitset>
void set_in_range(Bitset& b, unsigned value, int from, int to)
{
  for (int i = from; i < to; ++i, value >>= 1)
    b[i] = (value & 1);
}

boost::dynamic_bitset<> b(56, 1);
set_in_range(b, 2019, 4, 15);


来源:https://stackoverflow.com/questions/9966814/boost-dynamic-bitset-put-an-integer-value-into-a-range-of-bits

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