Get/Set/Clear the ith Bit in C++ | Bit Manipulation C++

 Bit Manipulation C++

 To get the bit at the Ith position we can use the following code using the left shift operator.
We will make a number in which there will be only 1 at a single position that is ith and all the other position is 0. Now we will take '&' with the other number and hence in this way we can find the bit at the ith position.

Here is the code for the following problem.

#include<bits/stdc++.h>
using namespace std;

int getIthbit(int nint i){
    int mask=(1<<i);
    return (n & mask) ? 1 : 0;
}


int main() {
    //the number x 
    int x;
    cin>>x;
    // The position i
    int i;
    cin>>i;

    cout<<getIthbit(x,i);




return 0;
}


Output of the above code is




Clear the ith Bit in C++

To clear the ith bit what we can do is we can take & with 0 at that position only.

like  if we need to clear the bit at the first position of the number 1  1  1  0  1  1 so we do the following
   A:-     1  1  1  0  1  1 
   B:-     1  1  1  1  0  1
ans-      1  1   1 0  0  1


Here is the code for the following :
for making the number B what we can do is that we can left shift 1 i times and then take the negation of that.

Here is the code:

#include<bits/stdc++.h>
using namespace std;

int getIthbit(int nint i){
    int mask=(1<<i);
    return (n & mask) ? 1 : 0;
}

void clearithBit(int &nint i){
    int mask=~(1<<i);
    n=(n&mask);
    
}


int main() {
    //the number x 
    int x;
    cout<<"Enter the number x:";
    cin>>x;
    // The position i
    cout<<"Ente the position i:";
    int i;
    cin>>i;

    clearithBit(x,i);
    cout<<"The number is:"<<x<<endl;




return 0;
}

Here is the output:




Set the Ith Bit in a number

To do so we can do the same thing as above just changing few things like instead of taking & with the number we will take OR with the number.
Here is the code to the problem.

#include<bits/stdc++.h>
using namespace std;

int getIthbit(int nint i){
    int mask=(1<<i);
    return (n & mask) ? 1 : 0;
}

void setIthBit(int &n,int i){
    int mask=(1<<i);
    n= (n|mask);
}

void clearithBit(int &nint i){
    int mask=~(1<<i);
    n=(n&mask);
    
}


int main() {
    //the number x 
    int x;
    cout<<"Enter the number x:";
    cin>>x;
    // The position i
    cout<<"Ente the position i:";
    int i;
    cin>>i;

    setIthBit(x,i);
    cout<<"The number is:"<<x<<endl;




return 0;
}

Here is the Output of the following program







dsf
sdf

Post a Comment

0 Comments