# Tilde Operator in C++

In this tutorial, we will learn about the tilde (~) operator in C++. In C++ there are a total of 6 bitwise operators which are &(bitwise AND), |(bitwise OR), ^ (bitwise XOR), << (left shift ), >>(right shift) and ~(tilde) bitwise operator.

Bitwise operators are used to modify variables, taking into consideration the bit patterns that represent the values that they store. When bitwise operators are applied on bits, then the result we get is all ones become zeroes and all zeroes become ones.

Also, read: Check if a given number exists in an array in C++

## Tilde – a bitwise NOT operator

Tilde is a bitwise NOT operator in C++ that takes one number and complements all of its bits. Consider the diagrammatical representation of the tilde operator given below-

operand1 -> 1 0 1 1 ------- ~operand2 -> 0 1 0 0

The highest bit of an int variable is called the sign bit and if that bit is high the number is interpreted as negative. The result may be negative if the number is stored in the signed variable. We are assuming that numbers are stored in 2’s complement form. (encoding of positive and negative numbers is known as 2’s complement).

Consider the below example-

#include <bits/stdc++.h> using namespace std; int main() { int x = 4;//entering the number cout << " The bitwise complement of the entered number is " << ~x; return 0; }

**Output:**

The bitwise complement of the entered number is -5.

**Code Explanation-**

- We are given the number x=4, binary form of 4:- 0 1 0 0
- Bitwise complement operation on 4:- ~1 0 1 1
- The decimal value of 1 0 1 1 is 11 which is the expected output.
- The correct output is -5.

The compiler returns the 2’s complement of the value which we have entered.

Thus, in this article, we have gained knowledge about the tilde bitwise operator in C++.

## Leave a Reply