How to manipulate bits easily?

6 06 2008

We usually use & operator for checking bits in an integer value. Is there any easy method to manipulate bits? You can use STL bitset container. But it’s not a container like vector or list. So it does not have iterators.

The bitset should be initialized with the number of bits. See the sample code block below.

// Initialize bitset with number of bits required.
// Here its for holding an integer.
bitset<sizeof(int) * 8> IntegerBits = 12478;

// I wanna see the value in binary.
cout << "Binary of 12478 is :" << IntegerBits << endl;

// How many bits are present?
cout << "Number of bits:" << IntegerBits.size() << endl;

// Check whether 10th bit is set.
cout << "10th bit is:" << IntegerBits[10] << endl;

// Flip all bits and display.
cout << "Flipped Binary of 12478 is :" << IntegerBits << endl;

Now getting and manipulating bits is just like a breeze. nah?

Targeted Audience – Beginners.