Bitwise XOR ^
What you'll learn: How to use the "Exclusive OR" operator to compare bits and identify differences between two numbers.
The "One or the Other" Rule
The Bitwise XOR operator (represented by the caret symbol ^) stands for "Exclusive OR." It acts like a picky gatekeeper. When comparing two bits, it only outputs a 1 if the inputs are different. If the inputs are the same—whether they are both 0 or both 1—the result is 0.
Think of it like a light switch controlled by two people. If both people try to turn it ON (1 and 1), they clash, and the light stays OFF (0). If neither touches it (0 and 0), it stays OFF (0). The light only shines if exactly one person flips the switch.
How it works in C
When you use ^ between two integers in C, the computer aligns them vertically in their binary (0s and 1s) forms and applies this rule to every column.
0 ^ 0 = 01 ^ 1 = 0(The "Exclusive" part: two 1s cancel out!)1 ^ 0 = 10 ^ 1 = 1
A Concrete Example
Let’s look at what happens when we XOR the numbers 5 and 3 in a C program.
#include <stdio.h>
int main() {
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
/*
Calculation:
0 1 0 1 (5)
0 0 1 1 (3)
-------
0 1 1 0 (Result is 6)
*/
int result = a ^ b;
printf("Result of 5 ^ 3 is: %d\n", result);
return 0;
}
In the example above, the bits in the first and last positions were the same, so they became 0. The bits in the middle two positions were different, so they became 1.
Why is this useful?
XOR has a magical property: it is its own undo button. If you XOR a value against a "secret key," it scrambles the data. If you XOR the result against that same key again, the original value pops back out! This makes it a fundamental tool for simple encryption, checking for errors in data transmission, and even toggling specific settings in computer graphics without affecting the rest of the image.
Key takeaway
The XOR operator ^ returns a 1 only when the two bits being compared are different.