In this tutorial, you shall learn about Bitwise Complement Operator in C++ programming language, its syntax, and how to use this operator with the help of examples.

C++ Bitwise Complement

C++ Bitwise Complement Operator is used to perform complement operation for a given operand. Complement Operator takes only one operand, and that is on right side.

Syntax

The syntax for Bitwise Complement operation for x is

~x

The operand can be of type int or char. Bitwise Complement operator returns a value of type same as that of the given operands.

ADVERTISEMENT

Truth Table

The following table illustrates the output of Complement operation between two bits.

bit~bit
01
10

Examples

1. Bitwise Complement of an integer value

In the following example, we take an integer value in x, and find the bitwise complement of x.

main.cpp

#include <iostream>
using namespace std;

int main() {
    int x = 5;
    int result = ~x;
    cout << "Result : " << result << endl;
}

Output

Result : -6
Program ended with exit code: 0

2. Bitwise Complement of an char value

In the following example, we take a char value in x, and find the bitwise complement of x.

main.cpp

#include <iostream>
using namespace std;

int main() {
    char x = 'a';
    char result = ~x;
    cout << "Result : " << result << endl;
}

Output

Result : \236
Program ended with exit code: 0

Conclusion

In this C++ Tutorial, we learned what Bitwise Complement Operator is, its syntax, and how to use this operator in C++ programs, with the help of examples.