Clearing a bit needs BitwiseAND(&) operator so irrespective of existing bit in place, it clears when we operate with bitwise AND(&). Create a mask based on the bit position, say pos = 2, mask is ~(1<<2). Which means ~(0000 0100) = 1111 1011. So bitwise AND with this mask, can clear the bitposition 2 in given reg.
Likewise Setting a bit needs Bitwise OR(|) operator so it modifies the bit to 1 irrespective of the existing value inplace. Create a mask based on bit position, say pos = 2,mask is just (1<<2) i.e., 0000 0100.
#include <stdio.h>
unsigned char modifyBit(unsigned char reg, int pos, int mode) {
// Write your code here
if(mode ==0){
reg = reg & (~(1<<pos));
}
else if(mode == 1){
reg = reg | (1<<pos) ;
}
return reg;
}
int main() {
unsigned char reg;
int pos, mode;
scanf("%hhu %d %d", ®, &pos, &mode);
printf("%d", modifyBit(reg, pos, mode));
return 0;
}
Input
10 3 1
Expected Output
10