The Wayback Machine - https://web.archive.org/web/20240917133140/https://www.geeksforgeeks.org/cpp-bitwise-operators/
Open In App

Bitwise Operators in C++

Last Updated : 22 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

There are various Operators present in C++. Every Operator has a particular symbol as well as an Operation to perform. We have various categories of operators in C++.

  1. Arithmetic Operators
  2. Relational Operators
  3. Logical Operators
  4. Assignment Operators
  5. Bitwise Operators

In this article, we will learn about the Bitwise Operators in C++.

C++ Bitwise Operators

Bitwise Operators are the operators that are used to perform operations on the bit level on the integers. While performing this operation integers are considered as sequences of binary digits. In C++, we have various types of Bitwise Operators.

  1. Bitwise AND (&)
  2. Bitwise OR (|)
  3. Bitwise XOR (^)
  4. Bitwise NOT (~)
  5. Left Shift (<<)
  6. Right Shift (>>)

1. Bitwise AND (&)

Bitwise AND operation is performed between two integers, It will compare each bit on the same position and the result bit will be set(1) only and only if both corresponding bits are set(1). The symbol which is used to perform bitwise AND operation is &.

Example: we will perform a Bitwise operation between two numbers 7 and 4. In binary 7 will be represented as 111 and 4 will be represented as 100.

     1  1  1
& 1 0 0
------
1 0 0

as we can see in the above example only those bits are set bits whose corresponding bits (both) are set. Therefore 7&4=4

2. Bitwise OR (|)

If Bitwise OR operation is performed between two integers , It will compare each bit on same position and the result bit will be set(1) if any of corresponding bits are set(1). The symbol which is used to perform bitwise OR operation is |.

Example: we will perform bitwise OR operation between two numbers 7 and 4. in binary 7 will be represented as 111 and 4 will be represented as 100.

    1  1  1
| 1 0 0
------
1 1 1

as we can see in above example those bits are set bits whose atleast any one corresponding bit are set. Therefore 7|4=7.

3. Bitwise XOR (^)

If Bitwise XOR operation is performed between two integers , It will compare each bit on same position and the result bit will be set(1) if any of corresponding bits differ i.e. one of them should be 1 and other should be zero. The symbol which is used to perform bitwise XOR operation is ^.

Example: we will perform bitwise XOR operation between two numbers 7 and 4. in binary 7 will be represented as 111 and 4 will be represented as 100.

    1  1  1
^ 1 0 0
------
0 1 1

as we can see in above example those bits are set bits whose corresponding bits are different . Therefore 7^4=3.

4.Bitwise NOT (~)

The Bitwise NOT operation is performed on a single number. It change the current bit to it’s complement , i.e. if current bit is 0 then in result it will be 1 and if current bit is 1 then it will become 0. It is denoted by the symbol ~.

Example: We will perform bitwise NOT Operation on number 4. The number 4 is represented as 100 in binary.

~ 1 0 0
------
0 1 1

As we can see in result the bits whose initial value was 1 are 0 in result and vice-versa. Therefore Bitwise NOT of number 4 will be 3.

5.Left Shift (<<)

This operator shifts the bits of Integer to left side by specific number (As mentioned) . This left shift operation is equivalent to multiplying the integer by 2 power number of positions shifted. The symbol which is used to represent Left Shift Operator is <<.

Example: Consider we have an integer 5, and we will left-shift its bits by 2 positions. The operation will be represented as x << 2.

The number 5 is represented as 101 in binary. We will add some zeros at the beginning to left shift the bits. Therefore it will be represented as 00000101. Now , we will move all the bits two positions to left and we will fill the empty positions with 0. Therefore it will become 00010100 which is 20 . As mentioned earlier left shifting the number by two bits means multiplying it by 2 raised to 2 which is 4 . 5*4 = 20 shows the above mentioned statement.

6.Right Shift (>>)

This operator shifts the bits of Integer to right side by specific number (As mentioned) . This right shift operation is equivalent to dividing the integer by 2 power number of positions shifted. The symbol which is used to represent Left Shift Operator is >>.

Example: Consider we have an integer 16, and we will right-shift its bits by 2 positions. The operation will be represented as x >> 2.

The number 16 is represented as 10000 in binary. We will add some zeros at the beginning to right shift the bits. Therefore it will be represented as 00010000. Now , we will move all the bits two positions to right and we will fill the empty positions with 0. Therefore it will become 00000100 which is 4 . As mentioned earlier right shifting the number by two bits means dividing it by 2 raised to 2 which is 4 . 16*4 = 4 shows the above mentioned statement.

C++ Program Bitwise Operators

Below is the implementation of the topic:

C++
// C++ Program to demonstrate
// Bitwise Operator
#include <iostream>

using namespace std;

// Main function
int main()
{
    int a = 5; //  101
    int b = 3; //  011

    // Bitwise AND
    int bitwise_and = a & b;

    // Bitwise OR
    int bitwise_or = a | b;

    // Bitwise XOR
    int bitwise_xor = a ^ b;

    // Bitwise NOT
    int bitwise_not = ~a;

    // Bitwise Left Shift
    int left_shift = a << 2;

    // Bitwise Right Shift
    int right_shift = a >> 1;

      // Printing the Results of
    // Bitwise Operators
    cout << "AND: " << bitwise_and << endl;
    cout << "OR: " << bitwise_or << endl;
    cout << "XOR: " << bitwise_xor << endl;
    cout << "NOT a: " << bitwise_not << endl;
    cout << "Left Shift: " << left_shift << endl;
    cout << "Right Shift: " << right_shift << endl;

    return 0;
}

Output:

AND: 1
OR: 7
XOR: 6
NOT a: -6
Left Shift: 20
Right Shift: 2

Conclusion

In Conclusion, Bitwise Operators are used to perform operations on binary (bit) level. We have various kind of Bitwise Operators as AND, OR, XOR, NOT, left shift, and right shift operators in C++. By this operations manipulation of individual bits can be done very precisely Which is essential in low level data handling.



Similar Reads

reinterpret_cast in C++ | Type Casting operators
reinterpret_cast is a type of casting operator used in C++. It is used to convert a pointer of some data type into a pointer of another data type, even if the data types before and after conversion are different.It does not check if the pointer type and data pointed by the pointer is same or not. Syntax : data_type *var_name = reinterpret_cast &lt;
3 min read
unordered_set operators in C++ STL
Unordered_set provides two operators in C++ STL. These are: Syntax: 1. (unordered_set &amp;lhs == unordered_set &amp;rhs) 2. (unordered_set &amp;lhs != unordered_set &amp;rhs) These operators are discussed in detail below: unordered_set == operator in C++ STL The ‘==’ is an operator in C++ STL performs equality comparison operation between two unor
5 min read
C++ Pointer Operators
Prerequisite: Pointers in C++ A pointer variable is a variable that stores the address of another variable or in other a pointer variable points to the variable whose address is stored inside it. Syntax: int *pointer_name; There are mainly two types of Pointer operators mainly used: Address of operator (&amp;)The indirection operator/Dereference op
2 min read
C++ Arithmetic Operators
Arithmetic Operators in C++ are used to perform arithmetic or mathematical operations on the operands. For example, ‘+’ is used for addition, ‘-‘ is used for subtraction, ‘*’ is used for multiplication, etc. In simple terms, arithmetic operators are used to perform arithmetic operations on variables and data; they follow the same relationship betwe
3 min read
Input/Output Operators Overloading in C++
Operator Overloading is a part of Polymorphism, which enables the feature because of which we can directly use operators with user-defined classes and objects. To read more about this, refer to the article operator overloading in C++. Input/Output Operators(&gt;&gt;/&lt;&lt;) Overloading in C++ We can't directly use the Input/Output Operators (&gt;
2 min read
C++ Increment and Decrement Operators
Prerequisite: Operators in C++ What is a C++ increment Operator? The C++ increment operator is a unary operator. The symbol used to represent the increment operator is (++). The increment operator increases the value stored by the variable by 1. This operator is used for Numeric values only. There are two types of C++ increment Operator: Pre-Increm
4 min read
C++ Comparison Operators
Comparison operators are operators used for comparing two elements, these are mostly used with if-else conditions as they return true-false as result. There are mainly 6 Comparison Operators namely: Greater than (&gt;) : this operator checks whether operand1 is greater than operand2. If the result turns out to be true, it returns true or else retur
3 min read
C++ Relational Operators
In C++ programming language, we sometimes require to compare values and expressions. This comparison allows us to determine relationships, make decisions, and control the flow of our programs. The relational operators in C++ provide the means to compare values and evaluate conditions. In this article, we will learn about C++ relational operators an
4 min read
C++ Logical Operators
In C++ programming languages, logical operators are symbols that allow you to combine or modify conditions to make logical evaluations. They are used to perform logical operations on boolean values (true or false). In C++, there are three logical operators: Logical AND ( &amp;&amp; ) OperatorLogical OR ( || ) OperatorLogical NOT ( ! ) OperatorLet's
4 min read
Unary Operators In C++
Unary operators in C++ are those operators that work on a single value (operand). They perform operations like changing a value's sign, incrementing or decrementing it by one, or obtaining its address. Examples include ++ for increment, -- for decrement, + for positive values, - for negative values,! for logical negation, and &amp; for retrieving m
8 min read
Assignment Operators In C++
In C++, the assignment operator forms the backbone of many algorithms and computational processes by performing a simple operation like assigning a value to a variable. It is denoted by equal sign ( = ) and provides one of the most basic operations in any programming language that is used to assign some value to the variables in C++ or in other wor
7 min read
What are the Operators that Can be and Cannot be Overloaded in C++?
There are various ways to overload Operators in C++ by implementing any of the following types of functions: 1) Member Function 2) Non-Member Function 3) Friend Function List of operators that can be overloaded are: + - * ? % ? &amp; | ~ ! = &lt; &gt; += -= *= ?= %= ?= &amp;= |= &lt;&lt; &gt;&gt; &lt;&lt;= &gt;&gt;= == != &lt;= &gt;= &amp;&amp; ||
4 min read
Increment (Decrement) operators require L-value Expression
What will be the output of the following program? #include&lt;stdio.h&gt; int main() { int i = 10; printf(&quot;%d&quot;, ++(-i)); return 0; } A) 11 B) 10 C) -9 D) None Answer: D, None - Compilation Error. Explanation: In C/C++ the pre-increment (decrement) and the post-increment (decrement) operators require an L-value expression as operand. Provi
1 min read
Order of operands for logical operators
The order of operands of logical operators &amp;&amp;, || are important in C/C++. In mathematics, logical AND, OR, etc... operations are commutative. The result will not change even if we swap RHS and LHS of the operator. In C/C++ (may be in other languages as well)  even though these operators are commutative, their order is critical. For example
1 min read
const_cast in C++ | Type Casting operators
C++ supports following 4 types of casting operators: 1. const_cast 2. static_cast 3. dynamic_cast 4. reinterpret_cast 1. const_cast const_cast is used to cast away the constness of variables. Following are some interesting facts about const_cast. 1) const_cast can be used to change non-const class members inside a const member function. Consider th
4 min read
Overloading stream insertion (&lt;&gt;) operators in C++
In C++, stream insertion operator "&lt;&lt;" is used for output and extraction operator "&gt;&gt;" is used for input. We must know the following things before we start overloading these operators. 1) cout is an object of ostream class and cin is an object of istream class 2) These operators must be overloaded as a global function. And if we want to
2 min read
How to sum two integers without using arithmetic operators in C/C++?
Given two integers a and b, how can we evaluate the sum a + b without using operators such as +, -, ++, --, ...? Method 1 (Using pointers)An interesting way would be: C/C++ Code // May not work with C++ compilers and // may produce warnings in C. // Returns sum of 'a' and 'b' int sum(int a, int b) { char *p = a; return (int)&amp;amp;p[b]; } Despite
4 min read
Conditionally assign a value without using conditional and arithmetic operators
Given 4 integers a, b, y, and x, where x can assume the values of either 0 or 1 only. The following question is asked: If 'x' is 0, Assign value 'a' to variable 'y' Else (If 'x' is 1) Assign value 'b' to variable 'y'. Note: - You are not allowed to use any conditional operator (including the ternary operator) or any arithmetic operator (+, -, *, /)
6 min read
Written version of Logical operators in C++
Can we use keywords in place of operators in C++ ? Yes, certainly, we can. The ANSI C++ Standard has proposed keywords for several C++ operators . They originated in C in the header at the time when there were keyboards that couldn't type the required symbols like &&, !, || etc. In C++, they became alternate token just like regular tokens, except f
2 min read
Comparing String objects using Relational Operators in C++
If strings are compared using relational operators then, their characters are compared lexicographically according to the current character traits, means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered. Parameters : Two Strings required t
2 min read
Casting Operators in C++
Casting operators are used for type casting in C++. They are used to convert one data type to another. C++ supports four types of casts: static_castdynamic_castconst_castreinterpret_cast1. static_castThe static_cast operator is the most commonly used casting operator in C++. It performs compile-time type conversion and is mainly used for explicit c
5 min read
new and delete Operators in C++ For Dynamic Memory
Dynamic memory allocation in C/C++ refers to performing memory allocation manually by a programmer. Dynamically allocated memory is allocated on Heap, and non-static and local variables get memory allocated on Stack (Refer to Memory Layout C Programs for details). What are applications?  One use of dynamically allocated memory is to allocate memory
6 min read
Operators in C++
An operator is a symbol that operates on a value to perform specific mathematical or logical computations. They form the foundation of any programming language. In C++, we have built-in operators to provide the required functionality. An operator operates the operands. For example,  int c = a + b;Here, '+' is the addition operator. 'a' and 'b' are
13 min read
Left Shift and Right Shift Operators in C/C++
In C/C++, left shift (&lt;&lt;) and right shift (&gt;&gt;) operators are binary bitwise operators that are used to shift the bits either left or right of the first operand by the number of positions specified by the second operand allowing efficient data manipulation. In this article, we will learn about the left shift and right shift operators. Le
6 min read
Conversion Operators in C++
In C++, the programmer abstracts real-world objects using classes as concrete types. Sometimes, it is required to convert one concrete type to another concrete type or primitive type implicitly. Conversion operators play an important role in such situations. It is similar to the operator overloading function in class. In this article, we will learn
4 min read
C++ Bitwise Operator Overloading
Prerequisites: Operator OverloadingBitwise Operator in C/C++ In C++, there are a total of six bitwise operators. The six bitwise operators are bitwise AND (&amp;), bitwise OR (|), bitwise XOR (^), left shift (&lt;&lt;), right shift (&gt;&gt;), and bitwise NOT (~). The &amp; (bitwise AND) in C++ takes two numbers as operands and does AND on every bi
7 min read
Bitwise Hacks for Competitive Programming
Prerequisite: It is recommended to refer Interesting facts about Bitwise Operators How to set a bit in the number 'num': If we want to set a bit at nth position in the number 'num', it can be done using the 'OR' operator( | ). First, we left shift '1' to n position via (1&lt;&lt;n)Then, use the 'OR' operator to set the bit at that position. 'OR' op
14 min read
Bitwise Complement Operator (~ tilde)
Pre-requisite:Bitwise Operators in C/ C++Bitwise Operators in Java The bitwise complement operator is a unary operator (works on only one operand). It takes one number and inverts all bits of it. When bitwise operator is applied on bits then, all the 1's become 0's and vice versa. The operator for the bitwise complement is ~ (Tilde). Example: Input
3 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
11 min read
Article Tags :
Practice Tags :