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 image

      nicomp really 6 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!

    Click to Rate This Article