#include <stdio.h>
unsigned char modifyBit(unsigned char reg, int pos, int mode) {
if (mode == 1) {
// Set the bit at position 'pos'
return reg | (1 << pos);
} else {
// Clear the bit at position 'pos'
return reg & ~(1 << pos);
}
}
int main() {
unsigned char reg;
int pos, mode;
scanf("%hhu %d %d", ®, &pos, &mode);
printf("%d", modifyBit(reg, pos, mode));
return 0;
}An 8-bit register holds values from 0 to 255, represented in binary as 00000000 to 11111111. Each bit position (0 to 7) can be individually manipulated using bitwise operations.
🛠️ Step-by-Step Solving Approach
reg: the 8-bit register value (unsigned char)pos: the bit position to modify (0–7)mode: operation mode (1 to set, 0 to clear)pos is between 0 and 7mode is either 0 or 1reg | (1 << pos)1 left by pos bits to create a maskreg to set the bitreg & ~(1 << pos)1 left by pos bits to create a mask~ to get all 1s except the target bitreg to clear the bit🔍 Example Walkthrough
Input: reg = 10, pos = 3, mode = 1
10: 000010101 << 3 → 00001000reg | 00001000 → 00001010 → Decimal 10 (bit already set)Input: reg = 10, pos = 1, mode = 0
10: 000010101 << 1 → 00000010~00000010 → 11111101reg & 11111101 → 00001000 → Decimal 8
Input
10 3 1
Expected Output
10