Bitset Constructors [C++ Reference]
Keywords: stl,bitset,bitset_constructors
Date: 2009-10-10T06:41:45-0700

## Bitset Constructors

Syntax:

        #include <bitset>
        bitset();
        bitset( unsigned long val );
        explicit bitset( const string& str, string::size_type pos = 0, string::size_type n = string::npos );

Bitsets can be constructed with default values, from the bits in an unsigned long, or from string.

- The default value of a bit is 0.
- When an unsigned long argument is supplied, each bit in the integer is used to initialize the corresponding bit in the bitset (if any).
- A string argument does the same, except that the character '0' gives the bitvalue 0, the character '1' gives the bitvalue 1, and other characters cause an invalid_argument exception to be thrown. Note that this constructor is explicit. So no implicit type conversion from const char* to string is provided.

When creating bitsets, the number given in the place of the template determines how long the bitset is.

For example, the following code creates two bitsets and displays them:

     // create a bitset that is 8 bits long
     bitset<8> bs;
     // display that bitset
     cout << bs << endl;

     // create a bitset out of a number
     bitset<8> bs2( 131 );
     // display that bitset, too
     cout << bs2 << endl;

     // create a bitset out of a string
     bitset<8> bs3(string("10000000"));
     // display the integer value of that bitset
     cout << bs3.to_ulong() << endl;

When run, this code displays the following output:

     00000000
     10000011
     128