C++ program to isolate rightmost zero bit of a number

Program to isolate rightmost zero bit of a number in C++: Here, we are going to use bitwise operators to isolate rightmost zero bit in the binary representation of a given number.
Submitted by Saksham Bhayana, on January 07, 2019

Here we are going to use bitwise operators to isolate rightmost zero bit in the binary representation of a given number.

Problem Statement: To write a C++ program to isolate rightmost zero bit of a number.

Constraints: 1<=n<=100

Example:

    Input:
    Enter number: 11

    Output:    
    original number before isolating rightmost 0 bit: 11
    new number after isolating rightmost 0 bit: 4

Problem Explanation:

Suppose the given number is 11. Let’s denote rightmost zero bit by RZB.

Now the binary representation of 11 is:

    n = 00001011
    mask1 = 00001100 (add 1 to n)
    mask2 = 11110100 (bitwise complement of n)
    Binary representation of number after isolating RZB = mask1 & mask2
    mask1 & mask2 = 00000100
    Hence decimal representation of new number is 4.

This can be explained as follows:

When we add 1 to n the RZB is changed to 1 and all the bits to the right of RZB becomes zero and all the bits to the left are unchanged.

When we do bitwise complement of n, the RZB is changed to 1. The bits to the right of RZB become 0 and bits to the left are toggled.

Therefore to isolate the RZB we can do bitwise AND of the two masks as only the RZBis 1 in both the masks.

Algorithm:

  1. Input the number for which RZB is to be isolated.
  2. Create a mask1 by adding 1 to original number.
  3. Create a mask2 by performing bitwise complement of original number (toggle all bits).
  4. Perform bitwise AND of the two masks created i.e. mask1 & mask2.
  5. Output the result after bitwise AND in decimal form.

C++ Implementation:

#include <iostream>
using namespace std;

int isolate_rightmost_zerobit(int n)
{
	int mask1=n+1;          //add 1 to original number  
	int mask2=~(n);         // bitwise complement of original number
	return (mask1&mask2);   // new number after isolating rightmost 0 bit 
}

//driver program to check the code

int main() 
{
	int num;

	cout<<"Enter number: ";
	cin>>num;
	cout<<"original number before isolating rightmost 0 bit: "<<num<<endl;

	int new_number= isolate_rightmost_zerobit(num);

	cout<<"new number after isolating rightmost 0 bit: "<<new_number<<endl;

	return 0;
}

Output

Enter number: 11
original number before isolating rightmost 0 bit: 11
new number after isolating rightmost 0 bit: 4 




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.