Home Resource Centre Bitwise Operators In C++ Explained In Detail With Examples

Bitwise Operators In C++ Explained In Detail With Examples

An operator is a symbol or keyword that performs a specific function (such as arithmetic operations) on one or more operands. And an operand is a value/ variable/ entity that the operator manipulates. There are multiple types of operators in C++, including:

  • Arithmetic operators
  • Logical operators
  • Relational operators
  • Assignment operators
  • Increment operators
  • Ternary operators, etc.

However, we will focus only on bitwise operators in C++ for the purpose of this article. A bitwise operator is an operator that works on individual bits of a number. It allows you to directly manipulate the bits in an integer type, which can be useful in certain programming scenarios. There are many real-life use cases of bitwise operators. They can be used to perform low-level bit manipulation, such as setting, clearing, or toggling individual bits in a bit field, as well as more complex operations, such as encoding and decoding data and performing bitwise arithmetic.

Different Type Of C++ Bitwise Operators

There are six types of bitwise operators in the C++ language, as shown in the diagram above. We will discuss each of these bitwise operators in C++ with example programs in the sections ahead.

C++ Bitwise AND Operator

The bitwise AND operator is a binary operator in C++ that takes two operands and compares every bit of the two. It is denoted by a single ampersand (&) and results in Boolean values/ binary numbers o and 1. That is, if both the bits are 1, then it results is also 1; otherwise, the result is 0. 

Bitwise AND Truth Table

a

b

a & b

0

0

0

0

1

0

1

0

0

1

1

1

Now let's take a look at a C++ program that showcases the use of this operator and how it performs AND operation on every bit of the operands. 

Example:

Output:

a & b = 0

Explanation:

In this code,

  1. We begin by including the iostream file and the namespace std.
  2. Then in the main() function, we first declare two unsigned integer variables, a and b, and initialize them with the values ​​9 and 6, respectively.
  3. Next, we declare another unsigned integer variable called result, which stores the result of the bitwise operator AND on a and b. 
  4. Finally, we print the result to the console using the cout statement and close the program with a return 0.

Also read- References In C++ | Declare, Types, Properties & More (+Examples)

C++ Bitwise OR Operator

The bitwise OR operator is a binary operator in C++ that performs a bitwise OR on the sum of its two operands. The result of the operation is a binary number 1 if one of the components of the operand is 1 and 0 otherwise.

Bitwise OR Truth Table

a

b

a | b

0

0

0

0

1

1

1

0

1

1

1

1

Example:

Output:

a | b = 15

Explanation:

  1. We start by including the iostream and namespace std. 
  2. Then in the main() function, we declare two unsigned integer variables, a and b, and initialize them with the values ​​9 and 6, respectively.
  3. Next, we declare another unsigned variable result, which stores the result of the bitwise OR operator on a and b.
  4. At last, we use the cout statement to print the result and bring the execution to an end with the return 0 statement.

C++ Bitwise XOR Operator

In C++ programming, the bitwise XOR operator is represented by the circumflex/ caret/ hat symbol, i.e., (^). It is a binary operator, meaning it takes two operands. The XOR operator performs a bitwise exclusive XOR operation on each pair of corresponding bits in its operands. The result is a new value where each bit in the result is the XOR of the corresponding bits in the operands.

The bitwise XOR operator returns a 1 in each bit position where the corresponding bits of its two operands are different. In other words, the result is 1 if the two are different, 0 otherwise.

Bitwise XOR Truth Table

a

b

a ^ b

0

0

0

0

1

1

1

0

1

1

1

0

Let's examine an example of the implementation of the Bitwise XOR operator:

Example:

Output:

a ^ b = 12

Explanation:

In this example,

  1. After including the iostream file and using namespace, we create the main() function.
  2. In this, we declare three unsigned integer variables, a, b, and c. We initialize a and b with the values of 10 and 6, respectively. These have the binary representation of ‘1010’ and ‘0110’, respectively.
  3. The third variable c, here, stores the result of the bitwise XOR operations on integer values of a and b. That is, we compare the binary values ​​a and b with XOR (^) and store the result in c.
  4. Finally, we use the cout statement to print the result before closing the program with a return 0.
  5. The value of c is 1100 in binary and 12 in decimal. 

Bitwise Left Shift Operator In C++

There are two bitwise shift operators (or unary operators), one of which we will discuss in the next heading. The Bitwise leftshift operator is represented by a double less than sign, i.e., <<. The left shift operator shifts the bits of the left operand to the left by the number of positions specified by the right operand. The bit shift out of the left end is discarded, and the bit shifted in on the right end is set to 0.

Example:

Output:

a = 10
a << 2 = 40

Explanation:

In this example,

  1. We declare the unsigned variable a and assign it the value 10, which is 1010 in binary.
  2. We then use the left shift operator (<<) to shift the bits of variable a, two positions to the left.
  3. The result of this operation is stored in another variable, b. The value of b is 101000 in binary, which is 40 in decimal.
  4. We finally print the value of a and the result of the left shift operator on a with the cout statement and close the program with return 0.

Bitwise Right Shift Operator In C++

The right shift operator is represented by double greater than signs/ forward-facing arrows, i.e. (>>). The bitwise shift right operator shifts the bits of the left operand to the right by the number of positions specified by the right operand. Items shifted to the right are discarded, and items shifted to the left are set to 0.

Example:

Output:

a = 10
a >> 2 = 2

Explanation:

  1. Here, we declare an unsigned integer variable a, in the main function and assign it the value 10, which has a binary representation of 1010.
  2. We then use the right shift operator (>>) to shift the bits of a, two positions to the right.
  3. The result of the right shift operation is stored in another unsigned variable declared and names b. The binary digits for b are 0010, which is ‘2’ in decimal.
  4. Finally, we use the cout statement to print both a and b and close the program with the return 0.

Also read- Comment In C++ | Types, Usage, C-Style Comments & More (+Examples)

Bitwise NOT Operator

The bitwise NOT operator is also known as the bitwise complement operator. This is also a unary operator and is represented by the tilde symbol ~. The bitwise operator does not perform the bitwise sum of its operands. Instead, it changes every 0 bit to 1 and every 1 bit to 0. In other words, it flips the binary digits of its operand.

For example, the bit of 10 (which is 1010 in binary) would be 0101 in binary, which is the number 5 in arithmetic. Let's take a look at a code implementation of the same in the example below.

Example:

Output:

a = 10
~a = -11

Explanation:

In this example,

  • We declare an unsigned integer variable a, and assign it the value 10 in the int main function. We know that the binary representation of the number 10 is 1010.
  • Next, we declare another unsigned integer variable b, which will store the result of the complement operation on a. 
  • We finally use the cout statement to print both a and b and complete the execution with return 0.
  • The value of b is 0101 in binary and -11 in decimal, which is what gets printed on the output window. 

The 2's Complement

Two's complement is a way to represent signed numbers using binary numbers. In this method, the most significant bit of the binary number (MSB) is used to represent the number, 0 for the positive number and 1 for the negative number.

To get the addition of a negative number, you need to change all the bits of it (turn all 0s to 1s and all 1s to 0s), then add 1s. For example, to get the two's complement of the number -10, which is 11110110 in binary, change all its bits to 00001001 and add 1 to get 00001010, the two’s complement representation of 10.

Binary number

1’s complement

2’s complement

000

000 (+0) and 111 (−0)

000

001

110

111

010

101

110

011

100

101

100

011

100

Here’s an example:

A simple example of how to use two's complement to represent signed integers in C++. Let's say we want to represent the number -5 using two's complement.

  • Step 1: Convert the absolute value of the number to binary. The absolute value of 5 is 5, which is represented in binary as 0101.
  • Step 2: Invert all of the bits in the binary representation. Inverting 0101 gives us 1010.
  • Step 3: Add 1 to the inverted binary number. Adding 1 to 1010 gives us 1011.

Therefore, the two's complement representation of -5 in binary is 1011.

Check this out- Boosting Career Opportunities For Engineers Through E-School Competitions

What Is The Meaning Of Set Bit In C++?

Setting a bit in C++ means changing the value of a bit at a certain position to 1. We use the bitwise OR to set a bit at a specific position (pos) in a variable number, with a mask at position 1 and 0 at position 0 in another place.

Let's look at an implementation example to understand how this works properly.

Set Bit Example:

Output:

num= 7

Explanation:

  • We begin by including the iostream library and open the int main function.
  • In the function, we first declare an integer variable called num with the binary value 0111 (and decimal 7).
  • We declare another integer variable pos , and assign it a value of 1.
  • Next, we want to set the bit at position 1 to 1, so we create a mask variable with 1 at the second position using the left shift operator (<<).
  • Finally, we print the output using the cout statement.

After executing the code, num is updated to (0111 | 0010), which results in the binary value 0111 (decimal 7).

What Does Clear Bit Mean?

Clearing a bit in C++ means changing the value of a particular bit at a specific position to 0. To clear a bit at a specific position (pos) in a variable (say, num), we use the bitwise AND operator (&) along with a mask that has a 0 at the position and 1s everywhere else.

Clear Bit Example:

Explanation:

  • We have declared an integer variable num with the binary value 0111 (which is 7 in decimal).
  • Another variable pos is declared and initialized with 1.
  • We want to clear the bit at position 1 to 0, so we create a mask with 0 at the second position using the left shift operator (<<) and the bitwise NOT ‘~’ operator.
  • We then use the bitwise AND (&) operator to clear the bit at position 1 in num to 0.

After executing the code, num is updated to 0111 & 1101, which results in the binary value 0101 (decimal 5).

Conclusion

Bitwise operators in C++ provide a powerful and efficient way to manipulate individual properties of data types.

  • The bitwise operators are bitwise AND (&), bitwise OR (|), bitwise XOR(^), bitwise NOT(~), left shift(<<), and right shift(>>).
  • These operators can be used to perform operations such as setting or clearing individual bits, checking if a bit is set, swapping the values of two variables, and more.

When using bitwise operators in C++, it is important to ensure that the operands are of the correct data type and to be aware of potential overflows or negative assumptions. 

Frequently Asked Questions

Q. Does the complementary operator flip the whole sequence of code in C++?

The complement operator in C++ is represented by the tilde (~) symbol, and it performs a bitwise NOT operation on the operand. This unary operation flips all the bits in the operand. That is, if the operand is a number or a character, the complement operator will convert all the bits in the binary form representation of the operand.

However, it's important to note that the complement operator does not flip the whole sequence of code in the program. It just flips the bits in the operand that is being operated on. The complement operator can be useful in certain situations, such as when you need to invert the bits of a variable or when you want to set all the bits in a variable to a certain value.

Q. Can I use the left and right shift operators together in a code?

Yes, you can use both left and right shift operators together in your code. The left shift operator (<<) and the right shift operator (>>) can be used to shift the bits of an operand to the left or right, respectively, by a specified number of positions.

When used together, these operators can be used to perform complex bit manipulation operations. For example, you can use the left shift operator to set a bit to a particular value and the right shift operator to clear a bit to a particular value.

Q. What are unary operators in C++?

In C++, unary operators are operators that operate on a single operator. These operators can be used to perform many operations on a single value or variable, such as arithmetic, logic, and bitwise operations.

Some of the unary operators in C++ are: Unary plus (+), Unary minus (-), Increment (++) and Decrement (--), Logical NOT (!)

Q. Can I use the left shift and right shift operators for negative numbers?

For the left shift operator (<<), shifting a negative number to the left may result in undefined behavior. This is because the sign bit of a negative number is set to 1, and shifting the sign bit may change the sign of the number, leading to unpredictable results.

For the right shift operator (>>), the behavior depends on whether the variable being shifted is a signed or unsigned value. For signed values, the behavior is implementation-defined. This means that the result of the shift operation may differ between different compilers and platforms. However, most compilers use the arithmetic right shift, which preserves the sign of the number being shifted by copying the sign bit to the shifted positions.

Q. What is Bitwise XOR Operation?

The bitwise exclusive or (OR only) is a binary operator in C++ that compares two bitwise operations and returns the result with each set if the properties of the two operands are equal or different. The symbol for the bitwise XOR operator in C++ is the caret (^).

Q. What is a logical operator in C++?

In C++, logical operators are operators that operate on Boolean expressions and return a Boolean value. These operators are used to combine two or more Boolean expressions and test whether they are true or false.

Some of the logical operators in C++ are: Logical AND (&&), Logical OR (||), Logical NOT (!)

Q. What are bitwise operators in real life? State an example.

The bitwise operator can be used in many real-life examples apart from programming languages. Here are a few examples:

  • Image Processing: Bitwise users are often used in image processing to manipulate the pixels of the image. For example, the bitwise AND operator can be used to create masks that isolate certain colors or parts of an image.
  • Embedded Systems: Bitwise operators in C++ are often used in embedded programming to control hardware registers and I/O ports. For example, bitwise operators can be used to set or clear individual registers to control the behavior of devices or interact with sensors and actuators.

Q. What is the time complexity of bitwise operators?

The time complexity of bitwise operators in C++ is usually O(1). This means that the time used to perform these operations is fixed and does not depend on the size of the input data. This is because bitwise operators ( bit operations) work at the bit level and directly manipulate objects regardless of the size of the operands.

For example, the bitwise operator AND (&) performs a bitwise AND operation on all adjacent bit pairs in the operands, regardless of the number of bits in the operands. Similarly, the bitwise XOR (^) operator performs the bitwise-exclusive-or operation on each adjacent pair of bits in the operands, again without specifying the size of the operands.

Therefore, the time complexity of the bitwise manager is fixed and does not increase with the size of the input data.

This compiles the discussion on Bitwise operators in C++. You might also be interested in reading the following:

  1. Typedef In C++ | Syntax, Application & How To Use It (With Examples)
  2. Pointers in C++ | A Roadmap To All Types Of Pointers With Examples
  3. Dynamic Memory Allocation In C++ Explained In Detail (With Examples)
  4. Strings In C++ | Functions, How To Convert & More (With Examples)
  5. 51 C++ Interview Questions For Freshers & Experienced (With Answers)
Shivani Goyal
Manager, Content

I am an economics graduate using my qualifications and life skills to observe & absorb what life has to offer. A strong believer in 'Don't die before you are dead' philosophy, at Unstop I am producing content that resonates and enables you to be #Unstoppable. When I don't have to be presentable for the job, I'd be elbow deep in paint/ pencil residue, immersed in a good read or socializing in the flesh.

TAGS
Engineering Computer Science
Updated On: 24 Jul'23, 02:02 PM IST