Modify a bit at a given position
Last Updated :
18 Sep, 2023
Given a number n, a position p and a binary value b, we need to change the bit at position p in n to value b.
Examples :
Input : n = 7, p = 2, b = 0
Output : 3
7 is 00000111 after clearing bit at
2nd position, it becomes 0000011.
Input : n = 7, p = 3, b = 1
Output : 15
7 is 00000111 after setting bit at
3rd position it becomes 00001111.
We first create a mask that has set bit only
at given position using bit wise shift.
mask = 1 << position
Then to change value of bit to b, we first
make it 0 using below operation
value & ~mask
After changing it 0, we change it to b by
doing or of above expression with following
(b << p) & mask, i.e., we return
((n & ~mask) | (b << p))
Below is the implementation of above steps :
C++
C
#include <stdio.h>
int modifyBit( int n, int p, int b)
{
int mask = 1 << p;
return ((n & ~mask) | (b << p));
}
int main()
{
printf ( "%d\n" ,modifyBit(6, 2, 0));
printf ( "%d\n" ,modifyBit(6, 5, 1));
return 0;
}
|
Java
import java.io.*;
class GFG
{
public static int modifyBit( int n,
int p,
int b)
{
int mask = 1 << p;
return (n & ~mask) |
((b << p) & mask);
}
public static void main (String[] args)
{
System.out.println(modifyBit( 6 , 2 , 0 ));
System.out.println (modifyBit( 6 , 5 , 1 ));
}
}
|
Python3
C#
PHP
Javascript
<script>
function modifyBit(n, p, b)
{
let mask = 1 << p;
return (n & ~mask) |
((b << p) & mask);
}
document.write(modifyBit(6, 2, 0) + "<br/>" );
document.write(modifyBit(6, 5, 1));
</script>
|
Output :
2
38
Time Complexity : O(1)
Auxiliary Space : O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...