Toggle the Bit in an 8-bit Register

Code

#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", &reg, &pos);
    uint8_t result = toggle_bit(reg, pos);
    printf("%u", result);
    return 0;
}

Solving Approach

✅ Toggle Bit — Small & Compact Solution Approach

1️⃣ Create mask for target bit

1 << pos

This produces a value where only that bit is 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:

  • XOR with 1 → flips the bit
  • XOR with 0 → unchanged

So only the selected bit changes.

💡 Final One-Line Logic

return reg ^ (1 << pos);

✔ Inverts only the selected bit
✔ Other bits unchanged
✔ No condition required
✔ Constant time
✔ Embedded-friendly

 

 

 

 

 

Upvote
Downvote
Loading...

Input

6 1

Expected Output

4