0
0
Embedded Cprogramming~5 mins

XOR for toggling bits in Embedded C

Choose your learning style9 modes available
Introduction
XOR helps flip specific bits in a number without changing others. It's like a switch that turns bits on or off.
You want to turn a light on if it's off, or off if it's on, using bits.
You need to change a setting stored as bits without affecting other settings.
You want to quickly flip a bit in a device register in embedded systems.
You want to toggle flags in a status variable efficiently.
Syntax
Embedded C
variable = variable ^ mask;
The ^ symbol means XOR in C.
The mask has 1s where you want to toggle bits, 0s elsewhere.
Examples
This flips the last bit of x from 1 to 0.
Embedded C
int x = 0b00001111;
x = x ^ 0b00000001;  // toggles the last bit
This flips the top 4 bits of flags.
Embedded C
int flags = 0b10101010;
flags ^= 0b11110000;  // toggles the top 4 bits
Sample Program
This program starts with 4 LEDs on (bits 0-3 set). It toggles bits 0 and 2 using XOR. The output shows the state before and after toggling.
Embedded C
#include <stdio.h>

int main() {
    unsigned char led_state = 0b00001111;  // 4 LEDs on
    unsigned char toggle_mask = 0b00000101; // toggle LEDs 0 and 2

    printf("Before toggle: 0x%02X\n", led_state);
    led_state = led_state ^ toggle_mask;
    printf("After toggle: 0x%02X\n", led_state);

    return 0;
}
OutputSuccess
Important Notes
XOR toggles bits: if bit is 1, it becomes 0; if 0, it becomes 1.
Use XOR to flip bits without affecting others.
Remember to use the correct mask to toggle only desired bits.
Summary
XOR (^) flips bits where mask bits are 1.
It's useful for toggling flags or settings in embedded systems.
Always prepare a mask with 1s at bits you want to toggle.