0
0
Power-electronicsHow-ToBeginner · 3 min read

How to Toggle a Bit in Embedded C: Simple Guide

To toggle a bit in embedded C, use the bitwise XOR operator ^= with a mask that has a 1 in the bit position you want to toggle. For example, PORT ^= (1 << n); flips the nth bit of PORT from 0 to 1 or from 1 to 0.
📐

Syntax

The syntax to toggle a bit uses the bitwise XOR operator ^= combined with a bit mask created by shifting 1 to the target bit position.

  • PORT: The variable or register holding the bits.
  • ^=: Bitwise XOR assignment operator that flips bits where the mask has 1.
  • (1 << n): Creates a mask with only the nth bit set to 1.
c
PORT ^= (1 << n);
💻

Example

This example toggles the 2nd bit (bit index 1) of a byte variable PORT. It shows the value before and after toggling.

c
#include <stdio.h>

int main() {
    unsigned char PORT = 0b00000100; // Initial value: bit 2 is set
    int bit_to_toggle = 1; // Toggle bit 1 (second bit from right, zero-based)

    printf("Before toggle: 0x%02X\n", PORT);
    PORT ^= (1 << bit_to_toggle);
    printf("After toggle:  0x%02X\n", PORT);

    return 0;
}
Output
Before toggle: 0x04 After toggle: 0x06
⚠️

Common Pitfalls

Common mistakes when toggling bits include:

  • Using |= instead of ^=, which only sets bits but does not toggle.
  • Forgetting to use parentheses around the shift operation, causing wrong precedence.
  • Using the wrong bit index (remember bits are zero-based from the right).
c
#include <stdio.h>

int main() {
    unsigned char PORT = 0b00000100;
    int bit_to_toggle = 1;

    // Wrong: sets bit instead of toggling
    PORT |= (1 << bit_to_toggle);
    printf("After |= : 0x%02X\n", PORT);

    // Correct: toggles bit
    PORT ^= (1 << bit_to_toggle);
    printf("After ^= : 0x%02X\n", PORT);

    return 0;
}
Output
After |= : 0x06 After ^= : 0x04

Key Takeaways

Use the bitwise XOR operator ^= with a shifted 1 to toggle a specific bit.
Remember bits are zero-indexed from the right (least significant bit).
Always use parentheses around the shift operation to ensure correct precedence.
Avoid using |= when you want to toggle; it only sets bits.
Test your code by printing values before and after toggling to verify behavior.