Search code examples
c++std-bitset

Change integer in bitset


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.


Solution

  • 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.