#include <stdio.h> #include <stdint.h> uint8_t toggle_bit(uint8_t reg, uint8_t pos) { return reg ^ (1<<pos); } int main() { uint8_t reg, pos; scanf("%hhu %hhu", ®, &pos); uint8_t result = toggle_bit(reg, pos); printf("%u", result); return 0; }
1️⃣ Create mask for target bit
1 << pos
This produces a value where only that bit is 1.
1
Example (pos = 3):
00001000
2️⃣ Use XOR to toggle
reg ^ (1 << pos)
Why XOR?
Truth table:
0 ^ 1 = 1 1 ^ 1 = 0 0 ^ 0 = 0 1 ^ 0 = 1
Key rule:
So only the selected bit changes.
return reg ^ (1 << pos);
✔ Inverts only the selected bit✔ Other bits unchanged✔ No condition required✔ Constant time✔ Embedded-friendly
Test Cases
Test Results
Input
6 1
Expected Output
4