C++ Bitset With Example

Updated on March 8, 2018
sirama profile image

I am a software engineer. I have been come across C++,MFC, .net technologies. I like playing video games & reading books.

1. Bit Representation Class

The c++ bitset class is useful to represent the binary number as a collection of bits or I can say a set of bits. A bitset class instance can be created using integer value or string representation of a binary number. For Example consider the below picture:

Bit fields represented in set form
Bit fields represented in set form | Source

Here, the integer value 252 is represented in the binary form by utilizing 8-bit fields. The bitset class representation will look like the reverse as bit position is written starting from Left towards right. When you debug this is how the bit fields are shown as a set of fields (Refer the bit value in set braces). From the above picture, the bit position 2 (Bit value 1) in binary number representation occupies third lot counting from the right side. The bitset representation is shown as a reverse in the debugger. So do not get confused with these signs. To refer a particular bit in the bit set, we can use the operator [].

2. Constructing Bitset

A Bitset can be constructed from a string form of binary numbers or it can be constructed from an integer number. To use bitmap class #include the <bitset> and this is marked as 1 in the below code snippet. The code snippet marked as two shows creating the bitset instance by making use of default constructor. In the code snippet, bitset1 instance contains 8-bit parts and each initialized to zero. You can allocate the capacity of the bitmap by specifying it in the angle bracket. For Example bitset<16> provide room to store 16 bits.

Code snippet marked as three shows constructing the object using integer number. The binary form of the number 177 is represented as eight-bit set in the instance bitset2. Code snippet marked as four shows creating the bitset object by passing the string representation of binary bits to the constructor.

Constructing bitset
Constructing bitset | Source

Code snippet for the bitset construction given below:

//Constuct 01: 8 bits initialized to zero
bitset<8> bitset1;
cout << "Construction without any parameter. Content of bitset1 :" 
	<< bitset1 << endl;

//Construct 02: Construct it from a integer number
bitset<8> bitset2(177);
cout << "Constructor with int as parameter. Content of bitset2: " 
	<< bitset2 << endl;

//Construct 03: Construct it from string 
bitset<8> bitset3(string("11111100"));
cout << "Constructor with string parameter.Content of bitset3: " 
	<< bitset3 << endl;

3. Setting and Resetting Bits

The set and reset member function of bitset class is used to set or reset a particular bit in the bitset. The set function turns ON all the bits in the bitset. To set a particular bit we can pass the bit location as a function parameter. Simply, the set function is used to set a particular bit to 1. Similarly, the reset function call turns OFF the given bit in the bitset. Have a look at the below example:

Code Snippet: Setting and resetting bitset bits
Code Snippet: Setting and resetting bitset bits | Source

Code snippet for setting and resetting bits are given below:

//Usage 01: Set and Reset a bit in the bitset
bitset2.reset(); cout << bitset2 << endl;
bitset2.set(4); cout << bitset2 << endl;
bitset2.set(7); cout << bitset2 << endl;

bitset3.set();	cout << bitset3 << endl;
bitset3.reset(1); cout << bitset3 << endl;
bitset3.reset(2); cout << bitset3 << endl;

4. Testing the State of Bit

OK, we construct a bitset and set or reset a particular bit in the bitset. How do I check the status of a particular bit in the bitset object? The test function takes index location of the bit that needs to be tested. When a bit under test is in the turned-on position (i.e.) 1, then the function will return Boolean true otherwise, it returns false. The below code snippet iterates through the bit set and tests each bit status. Based on the test outcome, the bit is SET or Not SET is printed on the console output.

Getting status of Particular bit in the bitset instance
Getting status of Particular bit in the bitset instance | Source

Note that the size() function of the bitset class returns number of bits that participates in the bitset object. Below is code snippet:

//Usage 02: Testing a perticular Bit
cout << "Bitset3: " << bitset3 << endl;
for (int i=0; i<bitset3.size(); i++)
{
	if (bitset3.test(i))
		cout << "Bit " << i << " is Set" << endl;
	else
		cout << "Bit " << i << " is Not Set" << endl;
}

Do not get confused with count and size method. The count() method of the bitset object tells how many bits in the given bitset are in the turned-on state. The below code snippet shows that three bits are turned ON.

Below is the complete code and its output:

/* Example 01: Bitset
Explains the usage std::bitset
*/

#include <iostream>
#include <bitset>
#include <conio.h>

using namespace std;

void main()
{
	//Constuct 01: 8 bits initialized to zero
	bitset<8> bitset1;
	cout << "Construction without any parameter. Content of bitset1 :" 
		<< bitset1 << endl;

	//Construct 02: Construct it from a integer number
	bitset<8> bitset2(177);
	cout << "Constructor with int as parameter. Content of bitset2: " 
		<< bitset2 << endl;

	//Construct 03: Construct it from string 
	bitset<8> bitset3(string("11111100"));
	cout << "Constructor with string parameter.Content of bitset3: " 
		<< bitset3 << endl;

	//Usage 01: Set and Reset a bit in the bitset
	bitset2.reset(); cout << bitset2 << endl;
	bitset2.set(4); cout << bitset2 << endl;
	bitset2.set(7); cout << bitset2 << endl;

	bitset3.set();	cout << bitset3 << endl;
	bitset3.reset(1); cout << bitset3 << endl;
	bitset3.reset(2); cout << bitset3 << endl;

	//Usage 02: Testing a perticular Bit
	cout << "Bitset3: " << bitset3 << endl;
	for (int i=0; i<bitset3.size(); i++)
	{
		if (bitset3.test(i))
			cout << "Bit " << i << " is Set" << endl;
		else
			cout << "Bit " << i << " is Not Set" << endl;
	}

	//Usage 03: Number of bits set
	bitset3.reset();
	bitset3.set(2);
	bitset3.set(4);
	bitset3.set(5);
	cout << bitset3.count() << " Bit(s) set" << endl;
	getch();
}
Program Output
Program Output | Source

© 2015 sirama

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      Code 

      3 months ago

      well done

    • profile image

      manjula96dhadi@gmail.com 

      6 months ago

      Good explanation

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://owlcation.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)