Toggling bits with ^
What you'll learn: How to use the Bitwise XOR operator to flip specific bits between 0 and 1 like a light switch.
The Digital Light Switch
In C, the ^ symbol represents the Bitwise XOR (Exclusive OR) operator. While "Exclusive OR" sounds complex, its most practical use in programming is acting as a toggle switch.
Think of a hallway light. If you flip the switch, the light changes state: if it was off, it turns on; if it was on, it turns off. The XOR operator does exactly this to individual bits. If you XOR a bit with 1, that bit flips. If you XOR a bit with 0, it stays exactly as it was.
The Logic of XOR
The rule for XOR is simple: the result is 1 only if the two bits are different.
0 ^ 1 = 1(The bit changed!)1 ^ 1 = 0(The bit changed!)0 ^ 0 = 0(No change)1 ^ 0 = 1(No change)
By creating a "mask"—a number where only specific bits are set to 1—you can choose exactly which bits in your variable you want to flip without disturbing the others.
Seeing it in Code
Imagine you are writing software for a game character. You have a variable where the 3rd bit represents whether the character is "Invisible." You can toggle this state back and forth using the ^ operator.
#include <stdio.h>
int main() {
// Binary: 0000 (The character is visible)
unsigned char status = 0;
// We want to toggle the 4th bit (value of 8 in decimal)
// Binary mask: 1000
unsigned char mask = 8;
// Toggle the bit ON
status = status ^ mask;
printf("Status after first toggle: %d\n", status); // Outputs 8
// Toggle the same bit OFF
status = status ^ mask;
printf("Status after second toggle: %d\n", status); // Outputs 0
return 0;
}
In the example above, applying the same XOR operation twice brings the variable back to its original state. This makes ^ the perfect tool for features that need to be turned on and off repeatedly, such as settings, UI elements, or game states.
Key takeaway
Use the ^ operator with a bitmask to flip specific bits; XORing with 1 toggles a bit, while XORing with 0 leaves it unchanged.