15.8. Class bitset

Class bitset makes it easy to create and manipulate bit sets, which are useful for representing a set of bit flags. bitsets are fixed in size at compile time. Class bitset is an alternate tool for bit manipulation, discussed in Chapter 20.

The declaration

bitset< size > b;

creates bitset b, in which every on of the size bits is initially 0 (“off”).

The statement

b.set( bitNumber );

sets bit bitNumber of bitset b “on.” The expression b.set() sets all bits in b “on.”

The statement

b.reset( bitNumber );

sets bit bitNumber of bitset b “off.” The expression b.reset() sets all bits in b “off.”

The statement

b.flip( bitNumber );

“flips” bit bitNumber of bitset b (e.g., if the bit is “on”, flip sets it “off”). The expression b.flip() flips all bits in b.

The statement

b[ bitNumber ];

returns a reference to the bit bitNumber of bitset b. Similarly,

b.at( bitNumber );

performs range checking on bitNumber first. Then, if bitNumber is in range, at returns a reference to the bit. Otherwise, at throws an out_of_range exception.

The statement

b.test( bitNumber );

performs range checking on bitNumber first. If bitNumber is in range, test returns true if the bit is on, false it’s off. Otherwise, test throws an out_of_range exception.

The expression

b.size()

returns the number of bits in bitset b.

The expression

b.count()

returns the number of bits that are set in bitset b.

The expression

b.any()

returns true if any bit is set in bitset b.

The expression

Image

b.all()

returns true if all of the bits are set in bitset b.

The expression

b.none()

returns true if none of the bits is set in bitset b.

The expressions

b == b1
b != b1

compare the two bitsets for equality and inequality, respectively.

Each of the bitwise assignment operators &=, |= and ^= (discussed in detail in Section 20.5) can be used to combine bitsets. For example,

b &= b1;

performs a bit-by-bit logical AND between bitsets b and b1. The result is stored in b. Bitwise logical OR and bitwise logical XOR are performed by

b |= b1;
b ^= b2;

The expression

b >>= n;

shifts the bits in bitset b right by n positions.

The expression

b <<= n;

shifts the bits in bitset b left by n positions.

The expressions

b.to_string()
b.to_ulong()

convert bitset b to a string and an unsigned long, respectively.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.67.212