user1096734
user1096734

Reputation:

c++ bitset questions

I want to ask two C++ bitset questions.

(1) How to create a bitset with a specified length from a function argument? I mean, for example, I have a function

void f(int n)

And inside f, I need to create bitset<n> bs; Is this something doable?

(2) How to copy part of a bitset bs to form a new bitset? For example, given starting index i1 and ending index i2 where i1>=i2, I need to form a new bitset by copying those bits in bs from the least i2th significant bit exclusive to the least i1th significant bit inclusive (just to conform with STL convention).

Thank you.

Upvotes: 2

Views: 1468

Answers (3)

Philipp
Philipp

Reputation: 49792

For the first question: there is Boost.Dynamic Bitset which is exactly what you want.

For the second question: here I'd simply to a (bs >> i2) & ~bitset(i1 - i2).

Upvotes: 0

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132974

(1) Not doable with std::bitset, because the size needs to be a compile-time constant (integral constant expression). You can use boost::dynamic_bitset, or, alternatively, std::vector<bool> or std::vector<char>

(2) std::bitset does not a special constructor for what you're looking for. You will need to write an explicit loop. All the other options listed in (1), however, have a constructor taking two iterators.

Upvotes: 2

JS.
JS.

Reputation: 616

Can you use boost? If so then boost::dynamic_bitset might be what you need. If not then std::vector<bool> might work, internally it's stored as a bitset rather than a vector of bools, and you should be able to use std::copy to copy your ranges of bits.

Upvotes: 1

Related Questions