The Wayback Machine - https://web.archive.org/web/20241113192354/https://www.geeksforgeeks.org/bitwise-complement-operator-tilde/
Open In App

Bitwise Complement Operator (~ tilde)

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

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: ~ 0000 0011
Output: 1111 1100

Input: 1110 0111
Output: 0001 1000

The bitwise complement operator should be used carefully. The result of ~ operator on a small number can be a big number if the result is stored in an unsigned variable. And the result may be a negative number if the result is stored in a signed variable (assuming that the negative numbers are stored in 2’s complement form where the leftmost bit is the sign bit).

Input: 
n = 2
Binary form of 2 = 0010
Bitwise complement operation on 2 = ~ 0010 
                                                         = 1101 
1101 is equivalent to decimal value 13.

Expected output: 13
Correct Output : -3

The compiler returns the 2’s complement of the input value.

C++
// C++ program to implement 
// the above approach
#include <iostream>
using namespace std;

// Driver code
int main() 
{
  int a = 2;
  cout << "Bitwise complement of " << 
           a << " : " << ~a;
}
C
// C program to implement
// the above approach
#include <stdio.h>

// Driver code
int main() 
{
  int n = 2;
  printf("Bitwise complement of %d : %d",
          n, ~n);
  return 0;
}
Java
// Java program to implement 
// the above approach
import java.io.*;

// Driver code
class GFG 
{
    public static void main (String[] args) 
    {
        int a = 2;
        System.out.println("Bitwise complement of " + 
                            a + " : " + ~a);
    }
}
Python
# Python3 program to implement 
# the above approach

# Driver code
n = 2
print("Bitwise complement of {n} :",
       ~n)
C#
// C# program to implement  
// the above approach
using System;

class GFG{

static public void Main()
{
    int a = 2;
    
    Console.WriteLine("Bitwise complement of " + a + 
                      " : " + ~a);
}
}
JavaScript
<script>

// JavaScript program to implement  
// the above approach

// Driver code
let a = 2;
document.write("Bitwise complement of " +
               a + " : " + ~a);

// This code is contributed by Potta Lokesh

</script>


Output:

Bitwise complement of 2 : -3

Explanation:
The bitwise complement of 2 (~2) is -3 instead of 13, but why? 
When numbers are printed in base-10, the result of a NOT operation can be surprising. In particular, positive numbers can become negative and vice versa.

Let’s first find the binary representation of bitwise complement of 2 which is -3

The negative numbers are stored as the two’s complement of the positive counterpart.

2’s Complement:
Two’s complement is an operation on binary numbers. The 2’s complement of a number is equal to the complement of that number plus 1. 

Example:

Bitwise complement Operation of 2 (~ 0010 ): 1101

Calculate 2’s complement of 3: 
Binary form of 3 = 0011 
1’s Complement of 3 = 1100 
Adding 1 to 1’s complement = 1100 +1
2’s complement of 3 = 1101  

Note: 
The bitwise Complement of 2 is same as  the binary representation of -3 

Thus it can be concluded from the above example that-

  1. For any integer n, the bitwise complement of n will be -(n+1). since [ -(~(~n)-1) = -(n+1) ]
  2. Bitwise complement of N = ~N (represented in 2’s complement form).
  3. 2’complement of ~N= -(~(~N)+1) = -(N+1).


Similar Reads

Maximize Bitwise AND of first element with complement of remaining elements for any permutation of given Array
Given an array arr[] consisting of N integers, the task is to find the maximum value of Bitwise AND of the first element with the complement of remaining elements for any permutation of this array, i.e. A1 &(~A2) & (~A3) & ......& (~An) Examples: Input: arr[] = {1, 2, 4, 8, 16} Output: 16 Explanation: For the permutation {16, 1, 2,
8 min read
Total pairs in an array such that the bitwise AND, bitwise OR and bitwise XOR of LSB is 1
Given an array arr[] of size N. The task is to find the number of pairs (arr[i], arr[j]) as cntAND, cntOR, and cntXOR such that: cntAND: Count of pairs where bitwise AND of least significant bits is 1.cntOR: Count of pairs where bitwise OR of least significant bits is 1.cntXOR: Count of pairs where bitwise XOR of least significant bits is 1. Exampl
7 min read
Maximize count of pairs whose Bitwise AND exceeds Bitwise XOR by replacing such pairs with their Bitwise AND
Given an array arr[] consisting of N positive integers, replace pairs of array elements whose Bitwise AND exceeds Bitwise XOR values by their Bitwise AND value. Finally, count the maximum number of such pairs that can be generated from the array. Examples: Input: arr[] = {12, 9, 15, 7}Output: 2Explanation:Step 1: Select the pair {12, 15} and replac
9 min read
Calculate Bitwise OR of two integers from their given Bitwise AND and Bitwise XOR values
Given two integers X and Y, representing Bitwise XOR and Bitwise AND of two positive integers, the task is to calculate the Bitwise OR value of those two positive integers. Examples: Input: X = 5, Y = 2 Output: 7 Explanation: If A and B are two positive integers such that A ^ B = 5, A & B = 2, then the possible value of A and B is 3 and 6 respe
7 min read
deque::operator= and deque::operator[] in C++ STL
Deque or Double ended queues are sequence containers with the feature of expansion and contraction on both the ends. They are similar to vectors, but are more efficient in case of insertion and deletion of elements at the end, and also the beginning. Unlike vectors, contiguous storage allocation may not be guaranteed. deque::operator= This operator
4 min read
Operator Overloading '<<' and '>>' operator in a linked list class
Prerequisite: Operator Overloading in C++, Linked List in C++ C++ comes with libraries that provide ways for performing Input and Output. In C++, Input and Output are performed as a sequence of bytes, also known as streams. Input and Output stream are managed by the iostream library. cin and cout are the standard objects for the input stream and ou
4 min read
Why overriding both the global new operator and the class-specific operator is not ambiguous?
The below section deals about overload resolution as it helps in the fundamentals of overloading and overriding. Predict the output: C/C++ Code #include <iostream> using namespace std; class Gfg { public: void printHello() { cout << "hello gfg-class specific" << endl; } }; void printHello() { cout << "hello gf
5 min read
vector::operator= and vector::operator[ ] in C++ STL
Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. vector::operator=This operator is used to assign new contents to the container by replacing the existing contents. It also modifies the size according to the new
4 min read
Previous number same as 1's complement
Given a number check whether binary representation of its predecessor and its 1's complement are same or not. Examples: Input : 14 Output : NO Storing 14 as a 4 bit number, 14 (1110), its predecessor 13 (1101), its 1's complement 1 (0001), 13 and 1 are not same in their binary representation and hence output is NO.Input : 8 Output : YES Storing 8 a
4 min read
Check if bits in range L to R of two numbers are complement of each other or not
Given two non-negative numbers a and b and two values l and r. The problem is to check whether all bits at corresponding positions in the range l to r in both the given numbers are complement of each other or not. The bits are numbered from right to left, i.e., the least significant bit is considered to be at first position.Examples: Input: a = 10,
8 min read
10's Complement of a decimal number
Given a decimal number N. The task is to find 10’s complement of the number N.Example: Input : 25 Output : 10's complement is : 75 Input : 456 Output : 10's complement is : 544 10’s complement of a decimal number can be found by adding 1 to the 9's complement of that decimal number. It is just like 2s complement in binary number representation.Math
4 min read
Complement of a number with any base b
In this post, a general method of finding complement with any arbitrary base [Tex]b [/Tex]is discussed. Remember: It is recommended to go through below as follows: One’s Complement of an Integer1’s and 2’s complement of a Binary Number Steps to find (b-1)’s complement: To find (b-1)’s complement, Subtract each digit of the number from the largest n
6 min read
2's complement for a given string using XOR
Given a binary string, task is to convert this string in to two's complement with the help of XOR operator. Examples: Input : 00000101Output :11111011 Input : 10010Output : 01110 We have discussed an approach in previous post to find 2's complement For 2’s complement, we first find one’s complement. We traverse the one’s complement starting from LS
6 min read
Visualizing the complement of a graph using networkx
Given a graph G complement of the graph is obtained by removing the edges contained in G from the complete graph having the same number of nodes as G. Example: Initial Graph G: The complement of G: Realizing Complement using Python : We will use networkx.complement() function for our task Syntax: networkx.complement() Returns the complement of the
2 min read
Find One’s Complement of an Integer | Set 2
Given an integer N, find the one’s complement of the integer. Examples: Input: N = 5Output: 2Explanation: Binary representation of 5 is "101". Its one's complement is "010" = 2. Input: N = 255Output: 0 Input: N = 26Output: 5 Approach: Already the XOR-based approach and converting the number to binary number approaches are mentioned in Set-1 of the
3 min read
Complement of Base 10 Integer
Given a base 10 integer N, the task is to find the 1's complement of this Base 10 Integer. Examples: Input: N = 5Output: 2Explanation: Binary representation of 5 is "101". Its one's complement is "010" = 2. Input: N = 255Output: 0 Approach: Here the number is converted by flipping bits and adding that power of 2 to the answer. Follow the steps ment
3 min read
Reverse complement of DNA strand using Python
In this article, we will cover, how to Reverse the complement of DNA or RNA sequences in Python. Example: DNA strand: ATGCCGAGCA Complementary Strand: TACGGCTCGT Reverse-Complementary strand: ACGAGCCGTAAn overview of DNA and RNA as used in Molecular Biology The genetic material of living organisms is made up of Deoxyribonucleic acid(DNA) or Ribonuc
6 min read
Shortest path in a complement graph
Given an undirected non-weighted graph G. For a given node start return the shortest path that is the number of edges from start to all the nodes in the complement graph of G. Complement Graph is a graph such that it contains only those edges which are not present in the original graph. Examples: Input: Undirected Edges = (1, 2), (1, 3), (3, 4), (3
11 min read
Find relative complement of two sorted arrays
Given two sorted arrays arr1 and arr2 of size m and n respectively. We need to find relative complement of two array i.e, arr1 - arr2 which means that we need to find all those elements which are present in arr1 but not in arr2. Examples: Input : arr1[] = {3, 6, 10, 12, 15} arr2[] = {1, 3, 5, 10, 16}Output : 6 12 15The elements 6, 12 and 15 are pre
10 min read
1's and 2's complement of a Binary Number
Given a Binary Number as a string, print its 1's and 2's complements. 1’s complement of a binary number is another binary number obtained by toggling all bits in it, i.e., transforming the 0 bit to 1 and the 1 bit to 0.In the 1's complement format , the positive numbers remain unchanged . The negative numbers are obtained by taking the 1's compleme
9 min read
Efficient method for 2's complement of a binary string
Given a Binary Number as string, print its 2's complements.2’s complement of a binary number is 1 added to the 1’s complement of the binary number. Note that 1's complement is simply flip of given binary number. Examples: 2's complement of "0111" is "1001" 2's complement of "1100" is "0100" We strongly recommend that you click here and practice it,
6 min read
Check if binary representation of a given number and its complement are anagram
Given a positive number you need to check whether it's complement and the number are anagrams or not.Examples: Input : a = 4294967295 Output : Yes Binary representation of 'a' and it's complement are anagrams of each other Input : a = 4 Output : No Simple Approach: In this approach calculation of the complement of the number is allowed.1. Find bina
9 min read
Check if one of the numbers is one's complement of the other
Given two non-negative integers a and b. The problem is to check if one of the two numbers is 1's complement of the other. The ones' complement of a binary number is defined as the value obtained by inverting all the bits in the binary representation of the number (swapping 0s for 1s and vice versa). Examples: Input : a = 10, b = 5 Output : Yes (10
6 min read
9's complement of a decimal number
9's complement of a decimal number is the subtraction of it's each digits from 9. Like 1's complement, 9's complement is used to subtract a number using addition.For example, let us compute value of "718 - 123" using 9's complement and addition. We first find 9's complement of 718 which is 281. Now we add 281 to 123. We get 404. 9's complement of t
4 min read
Find One's Complement of an Integer
Given an integer n, find the one's complement of the integer. Examples: Input : n = 5 Output : 2 Input : n = 255 Output : 0 Input : n = 26 Output : 5Recommended PracticeOne's ComplementTry It! Basic Approach : The naïve approach to solve the problem would be to first convert the given number into its binary representation and then change every 1's
7 min read
Proof: Why Probability of complement of A equals to one minus Probability of A [ P(A') = 1-P(A) ]
Probability refers to the extent of the occurrence of events. When an event occurs like throwing a ball, picking a card from the deck, etc., then there must be some probability associated with that event. Basic Terminologies: Random Event-If the repetition of an experiment occurs several times under similar conditions, if it does not produce the sa
4 min read
Unset he rightmost set bit using 2s complement
Given The task is to unset the rightmost set bit of N.Examples: Input: N = 5 Output: 4Explanation:101(5) -> 100(4)Input : N = 78Output : 76Explanation:1001110(78) -> 1001100(76)We have discussed Different Approaches Unset the LSB. In this post, we are going to discuss a new approach using two's complement. Obtain 2's complement of the number
3 min read
Complement of Graph
Consider a set A and U denotes the universal set then complement of set A can be found by Ac =U-A.But, a graph G(v, e) is a set of vertices and edges, is it possible to find the Complement of a graph? This question is answered below. The complement of a graph G, denoted as G', is defined such that it shares the same set of vertices as G, but its ed
5 min read
Multiply any Number with 4 using Bitwise Operator
We are a Number n and our task is to multiply the number by 4 using a bit-wise Operator. Examples: Input : 4 Output :16 Input :5 Output :20 Explanation Case 1:- n=4 the binary of 4 is 100 and now shifts two bit right then 10000 now the number is 16 is multiplied 4*4=16 ans. Approach :- (n<<2) shift two bit right C/C++ Code // C++ program to m
3 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 (&), bitwise OR (|), bitwise XOR (^), left shift (<<), right shift (>>), and bitwise NOT (~). The & (bitwise AND) in C++ takes two numbers as operands and does AND on every bi
7 min read
three90RightbarBannerImg