#include <stdio.h>
unsigned char modifyBit(unsigned char reg, int pos, int mode) {
// Write your code here
if(mode==1){
reg=reg|(1<<pos);
}
else if(mode==0){
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;
}The solution relies on two essential bitwise operators in C:
|): Used to set a bit. The result of A | B is 1 if at least one of the bits in the corresponding position of A or B is 1.X | 0 is XX | 1 is 1 (this is the key to setting the bit)&): Used to clear a bit. The result of A & B is 1 only if both bits are 1.X & 1 is XX & 0 is 0 (this is the key to clearing the bit)<<): Used to create a mask (a number with a single '1' at the desired position). 1 << N creates a value where only the Nth bit is '1'.~): Used to invert a mask for clearing a bit. ~Mask turns the '1' in the mask into a '0', and all the '0's into '1's.Logic for Setting a Bit
To set a specific bit at position pos, we need a mask where only that bit is 1, and then we use the | operator with the register value.
Steps:
1 << pos. This puts a 1 at the desired bit position and 0 everywhere else.1 << 3 results in 00001000.|) between the register and the mask. The 0s in the mask leave the other bits of the register unchanged, while the 1 in the mask forces that specific bit to become 1.register_value = register_value | (1 << pos);Logic for Clearing a Bit
To clear a specific bit at position pos, we need a mask where only that bit is 0, and then we use the & operator with the register value.
Steps:
1 << pos.1 << 3 results in 00001000.~) to flip all the bits. The 1 becomes 0, and all other 0s become 1s.~(00001000) results in 11110111.&) between the register and the inverted mask. The 1s in the mask leave the other bits of the register unchanged, while the 0 in the mask forces that specific bit to become 0.register_value = register_value & (~(1 << pos));
Input
10 3 1
Expected Output
10