Modify bit of a no. “n” at position “p” by “value”(0,1);
1 min readNov 20, 2019
n=(n& ~(1UL<<p))|(value<<p);
Example:
let n=15(1111)
here bit position p is supposed from right to left (3,2,1,0)
p=2
Step 1: x=1UL<<p=100;(clearing the bit at position p)
Step 2: ~x=011(1’s compliment)
Step 3: n&(1UL<<p)=1011;
value =0;
Step 4:value<<p=0;
Step 5:n&(1UL<<p)|(value<<p)=1011;
n=(n&(1UL<<p))|(value<<p)=1011;
c++ function
int modify(int n,int pos,int value){
n=(n&(1UL<<p))|(value<<p);
return n;
}