# Update the bit in the given position or Index of a number using C++

C++Server Side ProgrammingProgramming

In the given problem, we have to update the bit of the given index of a number. To update the number, we can use Bit Manipulation operation on a given number. For example,

Input-1

N= 25
bit= 1
position= 2

Output

29

Explanation − Since the given input 25 can be written in binary as ‘11001’ whereas the position index is ‘2’ and the bit is ‘1’. After replacing the digits at the given position the output will be ‘11101’ which is equivalent to ‘29’.

## Approach to solve this problem

In the given position or index of a number, the task is to update the bit with the particular bit given in the input. The approach to update the bit at the given position is first to clear the bit at the given position and then perform a Binary AND operation to update the bit.

• Take Input a number N, bit to update as ‘bit’ and position or index on which we have to update the bit as ‘position’.

• A void function updateBit(int &n, int bit, int position) takes the address of the current bit, bit value and the index of the bit. The function will print the updated value of the number by replacing the bit with the given one.

• Clear the bit at the given position and add the resultant bit to the result.

• Create a mask and perform an AND operation with the result.

• Perform Binary OR operation with the mask we have created and perform the right shift operation with the value to be updated at the index.

## Example

Live Demo

#include<iostream>
using namespace std;
void updateBit(int &n,int bit, int pos){
int clearBit= ~(1<<pos);
}
int main(){
int n=25;
int bit=1;
int pos=2;
updateBit(n,bit,pos);
cout<<n;
}

## Output

Running the above code will generate the output as,

29

Since the input is 25 which is 11001 in binary representation. After replacing the position which is ‘2’ with ‘1’, it will become 11101 in binary which is 29.

Published on 05-Feb-2021 10:45:15