How to Turn OFF or Turn ON all bits in C++

As the title of this blog suggests we are going to learn how to Turn OFF/ON all the bits of particular number in C++ using the Bitwise Not Operator.

Turning OFF/ON bits means to take complement of all the bits present in the binary form of the number. As we know that negative numbers are stored as the two’s complement of the positive counterpart. Now to Turn OFF/ON the bits we use Bitwise Not ( ~ ), commonly known as One’s Complement. We will take an example to understand how the Bitwise Not or One’s Complement work in C++.

 

Exempli Gratia(e.g.) : 0000 0010 is the binary equivalent of the decimal number 2, taking a complement of it’s binary equivalent we get 1111 1101.

Now take a look at the binary equivalent of 3 i.e. 0000 0011 now taking a compliment of it’s binary equivalent we get 1111 1100 and adding a +1 to it we get 1111 1101, which is the binary equivalent of -3.

From this we can yield the result that ~2 = -3, and therefore a general result can be observed i.e. ~n = -(n+1).

C++ program to Turn OFF/ON all bits of number

#include <iostream>
using namespace std;

int main()
{
  int num1 = 10;
  int num2 = 0;

  num2 = ~num1;
  cout << "Value of num2 is: " << num2 << endl;
  

  return 0;
}

There is also a keyword present in C++, compl which stands for complement and it can be used as an alternative to Bitwise Not ( ~ ).

num2 = compl num1;

Output :

Value of num2 is: -11

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *