ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

A Practical Introduction to Bitwise Operators in C Plus Plus

Updated on August 27, 2009

A Practical Introduction to Bitwise Operators in C Plus Plus

In this tutorial we introduce C++ bitwise operators and their applications.

A complete working program follows. The target compiler is Microsoft C++ under Microsoft Visual Studio.

A bitwise operator allows a programmer to access individual bits in a data item. The smallest data type in C++ is a byte or character. These special operators support setting, clearing, and evaluation of single bits in a byte or char data item. The operators can also be applied to larger data types if necessary.

The unsigned data types, namely unsigned char, unsigned int, and unsigned long, are commonly used in conjunction with bitwise operators. For example;

unsigned long gamma;
unsigned int alpha;
unsigned char beta;

Bitwise Operators in C++
Bitwise Operators in C++

"Signed" is the default when declaring integer types (char, int, long). Therefore, it is good practice to include the keyword "unsigned" when declaring data items that will be used in conjunction with bitwise operators. The exposure when combining signed data types and bitwise operators involves a mathematical operation called sign extension. There is no prohibition against using signed data items, however care must be taken to account for the sign extension operations and to code for them accordingly.

A Practical Introduction to Bitwise Operators in C Plus Plus

 * Bitwise operators                                                main.cpp *
 * Author: nicomp                                                            *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 * Description: Illustrations of concepts related to bitwise operators in C++*
 *                                                                           *
#include <iostream>
using namespace std;
void main()
//	Usually we will use unsigned integer data types when we manipulate bits
	unsigned char charBits;
	unsigned int  intBits;

//	If we use signed integer data types,
//       we cannot use the MSB; it is the sign bit

//	Bits are numbered from right to left starting from zero
//	The LSB is always bit zero
//	The bit number represents the corresponding power of 2 for that bit
//	Bit numbering for a char data item:

//	7654 3210
//	xxxx xxxx	(8 bits)

//	We write the bits in groups of 4 (nibbles) because...
//	1. They are easier for us to read that way.
//	2. 4 bits represent one hexadecimal digit.

//	0000	0	|	0100	4	|	1000	8	|	1100	C
//	0001	1	|	0101	5	|	1001	9	|	1101	D
//	0010	2	|	0110	6	|	1010	A	|	1110	E
//	0011	3	|	0111	7	|	1011	B	|	1111	F

//	There are three bitwise operators:
//	AND &
//	OR	|
//	XOR	~

//	We can turn on individual bits with the OR operator:

	charBits = 0;
//	Turn on bit 0
	charBits = charBits | 0x01;		// 0x01 is our mask
	cout << "\n unsinged char with Bit 0 turned on is " << hex << unsigned int(charBits);

//	We can turn on off bits with the AND operator:

	charBits = 0xff;				// start with all bits on
//	Turn off bit 7
	charBits = charBits & 0x7f;		// 0x7f is our mask
	cout << "\n unsinged char with Bit 7 turned off is " << hex << unsigned int(charBits);

//	We can do memory mapped I/O this way
	unsigned char charEngineControl;	// 8 bits mapped to 8 hardware I/O points

//	The bits are mapped according to the hardware configuration.
//	For this example we will assume this mapping:
//	Bit		Meaning

//	These 4 bits are inputs
//	0		Engine Warmed Up
//	1		A/C Clutch engaged
//	2		Oxygen Sensor Failed			If the O2 sensor fails, the hardware will set this bit. We will read it.
//	3		Driver Trapped in Trunk

//	These 4 bits will be outputs
//	4		Turn on Seat Belt Warning Light
//	5		Engage A/C Clutch
//	6		Deploy Air Bags					If we set this bit, the hardware will open the trunk
//	7		Open Trunk

//	Create bit masks to read the individual inputs
const unsigned char maskEngineWarmedUp = 0x01;
const unsigned char maskACClutchEngaged = 0x02;
const unsigned char maskO2SensorFailed = 0x04;
const unsigned char maskDriverTrappedInTrunk = 0x08;

//	Create bit masks to turn ON the individual outputs
const unsigned char maskTurnOnSeatBeltWarningLight = 0x10;
const unsigned char maskEngageACClutch = 0x20;
const unsigned char maskDeployAirBags = 0x40;
const unsigned char maskOpenTrunk = 0x80;

//	Create bit masks to turn OFF the individual outputs
const unsigned char maskTurnOffSeatBeltWarningLight = 0xef;		// every bit except bit 4: xxx0 xxxx
const unsigned char maskDisengageACClutch = 0xdf;				// every bit except bit 5: xx0x xxxx
//const unsigned char maskUnDeployAirBags = 0xbf;				// every bit except bit 6: x0xx xxxx
const unsigned char maskCloseTrunk = 0x7f;						// every bit except bit 7: 0xxx xxxx

//	Example: check to see if the O2 Sensor has failed by reading the appropriate bit
	if (charEngineControl & maskO2SensorFailed) cout << "O2 Sensor failed.";

//	Example: open the trunk by setting the appropriate bit
	charEngineControl |= maskOpenTrunk;		// Same as charEngineControl = charEngineControl | maskOpenTrunk

	cout<< "\nGet a free 7 day pass to Lifetime Fitness.\n\n";


    0 of 8192 characters used
    Post Comment

    • nicomp profile imageAUTHOR

      nicomp really 

      7 years ago from Ohio, USA

      Where did this come from (line 103) ?

      cout "\nGet a free 7 day pass to Lifetime Fitness.\n\n";

      I don't know why I would put that in the code!


    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, 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:

    Show Details
    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 or domains, for performance and efficiency reasons. (Privacy Policy)
    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)
    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.
    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)