Gold mine of Visual C++ tricks!
Archive for June 6, 2008
How to manipulate bits easily?
Jun 6th
![]()
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. IntegerBits.flip(); cout << "Flipped Binary of 12478 is :" << IntegerBits << endl;
Now getting and manipulating bits is just like a breeze. nah?
![]()
Targeted Audience – Beginners.