C++ program to toggle Kth bit of a number

Here, we are going to learn how to toggle Kth bit of a given number using C++ program (bitwise operator)?
Submitted by Saksham Bhayana, on December 22, 2018

Program to toggle the Kth bit of a number in C++: Here we are going to use bitwise operators to toggle Kth bit in the binary representation of a given number.

Problem Statement: To write a C++ program to toggle Kth bit of a number.

Constraints: 1<=n<=100

Example:

    
    Input:
    Enter number: 5
    Enter k: 2

    Output:
    original number before toggling: 5
    new number after toggling: 7

Problem Explanation:

Suppose the given number is 5 and the bit to be toggled is 2nd bit that is 1 left to the LSB.

Now the binary representation of 5 is:

    n = 00000101
    mask = 00000010 (left shift 1, one time (2-1) as k=2)
    Binary representation of number after toggling= n ^ mask
    n ^ mask = 00000111 
    Hence decimal representation of new number is 7.

This can be explained as follows:

Let Kth bit be X. Performing XOR with the mask toggles Kth bit only because:

If X is 0: 0^1 gives 1

If X is 1: 1^1 gives 0

For remaining bits of original number, XOR with 0 gives the bit itself.

Algorithm:

  1. Input the number and Kth bit to be toggled.
  2. Left shift 1 - (K-1) times to create a mask where only Kth bit is set.
  3. Perform bitwise XOR with this mask to toggle the Kth bit.
  4. Output the result after XOR in decimal form.

C++ Implementation:

#include <iostream>
using namespace std;

// K starts from 1
// left shift 1 K-1 times and xor with number n
// 1<<K-1 generates a mask in which only Kth bit is set.

int ToggleKthBit(int n,int K)
{                           
	return n ^ (1 << (K-1)); //toggled number
}

//driver program to check the code
int main() 
{
	int num,k;
	
	cout<<"Enter number: ";
	cin>>num;
	cout<<"Enter bit to toggle (value of k): ";
	cin>>k;

	cout<<"Enter number: "<<num<<endl;
	cout<<"Enter k: "<<k<<endl;

	cout<<"original number before toggling: "<<num<<endl;

	int new_number= ToggleKthBit(num,k);

	cout<<"new number after toggling: "<<new_number<<endl;
	
	return 0;
}

Output

Enter number: 5
Enter bit to toggle (value of k): 2
Enter number: 5
Enter k: 2
original number before toggling: 5
new number after toggling: 7



Comments and Discussions!

Load comments ↻





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