Home » C++ programs

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

Program to isolate rightmost one bit of a number in C++: Here, we are going to use bitwise operators to isolate rightmost one 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 one bit in the binary representation of a given number.

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

Constraints: 1<=n<=100

Example:

    Input:
    Enter number: 18

    Output:
    original number before isolating rightmost 1 bit: 18
    new number after isolating rightmost 1 bit: 2

Problem Explanation:

Suppose the given number is 18. Let’s denote rightmost one bit by ROB.

Now the binary representation of 18 is:

    n = 00010010
    mask = -n = 11101110 (toggle all bits and 1 to it)
    Binary representation of number after isolating ROB = n & mask
    n & mask = 00000010
    Hence decimal representation of new number is 2.

This can be explained as follows:

When we create a mask of -n, we observe that only ROB and bits to the right of ROB (which are 0) are identical to the original number.

Therefore, to isolate the ROB we can do bitwise AND of the mask with n as only the ROB is 1 in both the masks.

Algorithm:

  1. Input the number for which ROB is to be isolated.
  2. Create a mask -n (first toggle all bits in n and then add 1 to it).
  3. Perform bitwise AND of the mask created with original number i.e. n & mask where mask is of -n.
  4. Output the result after bitwise AND in decimal form.

C++ Implementation:

#include <iostream>
using namespace std;

int isolate_rightmost_onebit(int n)
{
	//to compute -n, toggle all bits and add 1 to it 
	int mask=-n;
	// new number after isolating rightmost 1 bit 
	return (n&mask);
}

//driver program to check the code
int main() 
{
	int num;

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

	int new_number= isolate_rightmost_onebit(num);

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

	return 0;
}

Output

Enter number: 18
original number before isolating rightmost 1 bit: 18
new number after isolating rightmost 1 bit: 2





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.