Find the position of rightmost unset bit of a number in C++

We all know everything on the computer is represented by 0’s and 1’s, be it a number or an alphabet, any image or a file. Such numbers are called binary bits. We know, a group of such 8 bits is known as a byte. Such a group of individual bytes can represent anything in the computer system. In this program, we are going to understand or rather find the position of rightmost unset bit or ‘0’ in the byte code of an integer number.

Illustration of the above program:

34 will be 100010 in binary code. This will have the unset bit or ‘0’ at the rightmost bit since it is an even number.

To translate integers to binary form we will not use bitwise operator because I don’t know how to use it. Instead, we will use the traditional method of dividing it by 2 repeatedly and find the first occurring unset bit.

Algorithm: Position of rightmost unset bit of a number in C++

  1. Insert an integer.
  2. start while(inserted num !=0)
  3. i=i+1(i is a counter variable that counts the position we find the unset bit, it is initialized as 0)
  4. remainder=inserted number%2
  5. inserted number=inserted number/2
  6. check if(remainder=0) then
  7. exit the while loop
  8. end if
  9. end while
  10. check if(inserted number=0) then
  11. print “No unset bit found”
  12. else
  13. print “Unset bit found in position”
  14. print i
  15. end if

Also read:

C++ Program to find the position of rightmost unset bit of a number

using namespace std;
int main()
    int num,rem,i=0;
    cout<<"Insert a number :";
        rem=num%2;               //This will give the remainder when divided by 2
        if(rem==0)               //We are searching for an unset bit here 
        cout<<"Sorry no unset bit found in number";
        cout<<"The unset bit is found in "<<i<<"th position";
    return 0;

The output:

find the position of rightmost unset bit of a number in C++

This is a very simple program. I tried my best to do it in the easiest way possible. Hope you like it. If you have any doubts, please comment below.

Leave a Reply

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