#include <stdio.h>
unsigned char modifyBit(unsigned char reg, int pos, int mode) {
// Write your code here
if (mode){
return reg | 1<<pos;
}
else{
return reg & ~(1<<pos);
}
return 0;
}
int main() {
unsigned char reg;
int pos, mode;
scanf("%hhu %d %d", ®, &pos, &mode);
printf("%d", modifyBit(reg, pos, mode));
return 0;
}
Excellent 👏🔥
Now we’ll discuss the solving approach, not just the answer — this is what interviewers care about.
Your code is correct ✅
Now let’s understand how to think before writing it.
Whenever you see a bit manipulation question, follow this structured method:
unsigned char reg
Visual model:
Bit: 7 6 5 4 3 2 1 0
Always visualize in binary first.
Inputs:
reg → original register
pos → which bit
mode → set or clear
Important:
👉 Only ONE bit must change
👉 All other bits must remain same
This means we cannot overwrite the whole number.
We must isolate and modify only one bit.
This tells us:
🚩 We need a bit mask
To isolate a bit:
1 << pos
Why?
Because:
1 = 00000001
Shift left by pos:
If pos = 3:
00001000
Now only that bit is 1.
This mask helps us target the bit.
Goal:
Force that bit to become 1.
We use:
reg | (1 << pos)
Why OR?
Because:
Anything OR 1 → 1
So that bit becomes 1.
Other bits stay unchanged.
Goal:
Force that bit to become 0.
Step 1:
Create mask:
00001000
Step 2:
Invert it:
11110111
Now use AND:
reg & ~(1 << pos)
Why AND?
Because:
Anything AND 0 → 0
Anything AND 1 → unchanged
So only that bit becomes 0.
After modification:
return reg;
Your implementation:
if (mode){
return reg | 1<<pos;
}
else{
return reg & ~(1<<pos);
}
✔ Correct
✔ Efficient
✔ Interview-ready
Whenever you see:
Memorize this mapping.
In real hardware:
GPIOA->ODR |= (1 << 5); // Set
GPIOA->ODR &= ~(1 << 5); // Clear
Same logic.
Registers are just numbers.
Each bit controls hardware.
Because bit operations are constant time.
Embedded systems prefer:
Bitwise operations are extremely fast.
Best formatted version:
unsigned char modifyBit(unsigned char reg, int pos, int mode) {
if (mode)
return reg | (1 << pos);
else
return reg & ~(1 << pos);
}
For ANY bit question:
1 << pos
Input
10 3 1
Expected Output
10