4

How does one change the integer being used by bitset? Suppose I used bitset to declare a variable mybitset which stores the bits of a number, say 32. After doing some operations, I want mybitset to store the bits of some other number, say 63. How do I achieve this?

I have added a small piece of sample code below to help explain.

bitset<32> mybits(32);
....
mybits(63);  // gives compilation error here, stating "no match for call to '(std::bitset<32u>) (uint&)'" 

I feel there should be some straightforward method to do this, but haven't been able to find anything.

therainmaker
  • 4,253
  • 1
  • 22
  • 41

4 Answers4

4

You can either use

mybits = bitset<32>(63);

as other answers have pointed out, or simply

mybits = 63;

The latter works because 63 is implicitly convertible to a bitset<32> (as the constructor from long is not marked as explicit). It does the same thing as the first version, but is a bit less verbose.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
toth
  • 2,519
  • 1
  • 15
  • 23
2

As from the reference documentation

bitset meets the requirements of CopyConstructible and CopyAssignable.

Thus you can simply assign from another std::bitset matching the same template parameter signature:

bitset<32> mybits(32);
// ....
mybits = bitset<32>(63);

or use one of the implicit constructors (2) along lvalue type deduction:

bitset( unsigned long val ); // (until C++11)
constexpr bitset( unsigned long long val );

and assign the value directly:

mybits = 63;
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
1

Just call: myBits = std::bitset<32>{63};

Elohim Meth
  • 1,777
  • 9
  • 13
1

A std::bitset is copy assignable, so you make a new one with the desired value and assign that to the bitset you want to change:

bitset<32> mybitset{21};
mybitset = bitset<32>{42};

If you don't want to specify the type once again, you could use decltype or even better the fact that bitsets constructor isn't explicit:

mybitset = {42};

(In action)

Daniel Jour
  • 15,896
  • 2
  • 36
  • 63