#include <stdio.h>
unsigned char modifyBit(unsigned char reg, int pos, int mode) {
if (mode == 1){
reg |= (1U << pos); // SET BIT
} else {
reg &= ~(1U << pos); // CLEAR BIT
}
return reg;
}
int main() {
unsigned char reg;
int pos, mode;
scanf("%hhu %d %d", ®, &pos, &mode);
printf("%d", modifyBit(reg, pos, mode));
return 0;
}
Solving Approach
The mode can either be 1 or 0, so an if-else statement must be used for each case. We need there to be code to either set/clear the bit we want to change.
If the mode is set to 1, use the bitwise OR operator on reg to shift the bit once to the left.
If the mode is set to 0, use the bitwise AND operator, and invert the bits using ~.