- How the
^operator computes the bitwise XOR of two integers - How binary representation matters for bitwise operations
- The bit-by-bit truth table:
1 ^ 1 = 0,0 ^ 0 = 0, otherwise1 - How XOR toggles bits — the "flip the switch" operator
- How XOR can swap two variables without a temporary
The bitwise XOR operator
The bitwise XOR (exclusive OR) operator ^ compares two integers bit by bit. For each bit position, if the two corresponding bits are different, the result bit is 1. If they're the same (both 0 or both 1), the result bit is 0. The name "exclusive" OR reflects that the result is 1 only when exactly one of the bits is 1 — not both.
XOR has some remarkable algebraic properties that make it indispensable in bit manipulation:
a ^ a = 0— XORing a value with itself always gives 0.a ^ 0 = a— XORing with 0 leaves the value unchanged.a ^ b = b ^ a— commutative.(a ^ b) ^ c = a ^ (b ^ c)— associative.a ^ b ^ b = a— XORing twice with the same value "undoes" the operation.
Common uses of ^:
- Toggling bits — flip a bit:
n ^ (1 << k)toggles bitk. - Swap without temp —
a ^= b; b ^= a; a ^= b;swaps two variables. - Finding the odd-one-out — XOR all elements in an array; the result is the unique element if all others appear in pairs.
- Simple encryption — XOR with a key, XOR again with the same key to decrypt.
- Checksums — XOR-based parity checks detect single-bit errors.
a ^ b sets each bit of the result to 1 only where a and b have different bits. It's the "toggle" or "difference detector" operator.
Truth table
For each pair of bits, the XOR result is:
| Bit a | Bit b | a ^ b |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
In words: the result is 1 when the two input bits differ, and 0 when they're the same. Applying this rule at every bit position gives the bitwise XOR.
For example, 12 ^ 10:
Reading bit by bit from left to right:
- Bit 3 (8's place): 1 ^ 1 = 0 (same)
- Bit 2 (4's place): 1 ^ 0 = 1 (different)
- Bit 1 (2's place): 0 ^ 1 = 1 (different)
- Bit 0 (1's place): 0 ^ 0 = 0 (same)
Result: 0110 in binary = 6 in decimal. So 12 ^ 10 = 6.
Complete C Program
Here is the program — bitwise XOR on two integers:
Program: Bitwise XOR of two integers
#include <stdio.h>
int main(void) {
int a, b, result;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
result = a ^ b;
printf("a = %d\n", a);
printf("b = %d\n", b);
printf("a ^ b = %d\n", result);
return 0;
}
A variant that also shows the binary representation:
Variant: Show binary representation
#include <stdio.h>
void print_binary(int n) {
for (int i = 7; i >= 0; i--) {
printf("%d", (n >> i) & 1);
if (i % 4 == 0 && i != 0) printf(" ");
}
printf("\n");
}
int main(void) {
int a, b, result;
printf("Enter two integers (0-255): ");
scanf("%d %d", &a, &b);
result = a ^ b;
printf("\na = ");
print_binary(a);
printf("b = ");
print_binary(b);
printf("a ^ b = ");
print_binary(result);
printf("\nDecimal result: %d\n", result);
return 0;
}
The print_binary helper iterates from bit 7 down to bit 0, using (n >> i) & 1 to isolate each bit — the AND operator appears here twice (once to compute the XOR result, once to extract bits for display). This is the standard way to display binary in C, since printf has no %b specifier.
A third variant demonstrating the classic XOR swap trick:
Variant: Swap two variables using XOR
#include <stdio.h>
int main(void) {
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
printf("Before swap: a = %d, b = %d\n", a, b);
a = a ^ b;
b = a ^ b; /* b now equals original a */
a = a ^ b; /* a now equals original b */
printf("After swap: a = %d, b = %d\n", a, b);
return 0;
}
This is a classic bitwise trick — swapping two integers without a temporary variable. The three XOR operations work because XOR is its own inverse: a ^ b ^ b = a. For modern compilers, the temp-variable swap is usually optimized to the same code (or better), so this is more of a puzzle/curiosity than a practical technique — but it's a great illustration of XOR's algebraic properties.
Program Output
Sample run of the basic program:
Enter two integers: 12 10
a = 12
b = 10
a ^ b = 6
As computed above: 12 (1100) ^ 10 (1010) = 0110 (6). Correct.
More examples:
Enter two integers: 5 5
a = 5
b = 5
a ^ b = 0
5 ^ 5 = 0 — XORing a value with itself always gives 0, because every bit matches. And:
Enter two integers: 7 0
a = 7
b = 0
a ^ b = 7
7 ^ 0 = 7 — XOR with 0 leaves the value unchanged, because 0 has no 1-bits to flip. These two identities (a ^ a = 0 and a ^ 0 = a) are the foundation of all XOR tricks.
The variant with binary display:
Enter two integers (0-255): 12 10
a = 0000 1100
b = 0000 1010
a ^ b = 0000 0110
Decimal result: 6
The binary view makes the operation obvious: the result has a 1 only in the positions where 12 and 10 differ (bits 1 and 2).
The XOR swap variant:
Enter two integers: 42 99
Before swap: a = 42, b = 99
After swap: a = 99, b = 42
The two values are swapped without a temporary variable — a demonstration of XOR's self-inverse property.
Step-by-Step Explanation
1. Declarations: int a, b, result; — bitwise XOR works on integers (or any integer type: char, short, long). The result has the same type as the operands after the usual arithmetic promotions.
2. Input: scanf("%d %d", &a, &b) reads two integers. The & here is the address-of operator, not the bitwise AND operator.
3. The XOR operation: result = a ^ b computes the bitwise XOR. Each bit of result is set to 1 if the corresponding bits of a and b are different. For 12 ^ 10: 1100 ^ 1010 = 0110 = 6.
4. Why is it useful? The XOR operator is the primary tool for toggling bits. For example:
n ^ (1 << k)— toggles bitk. If it was 0, it becomes 1; if it was 1, it becomes 0.n ^ 0xFF— flips all 8 low bits (bitwise NOT of the low byte).a ^ b ^ b— returnsa, since XOR is its own inverse.- Swapping two values:
a ^= b; b ^= a; a ^= b;.
5. Output format: %d prints the integer result in decimal. To see the binary, you'd need a custom function (as in the variant).
6. Precedence: The bitwise XOR has lower precedence than comparison operators, but higher precedence than bitwise OR. So a ^ b | c parses as (a ^ b) | c, not a ^ (b | c). When in doubt, use parentheses.
7. The XOR swap trick: The three lines a ^= b; b ^= a; a ^= b; swap a and b. Tracing through with a = 42, b = 99:
- After
a ^= b:aholds 42^99,bstill holds 99. - After
b ^= a:bholds 99^(42^99) = 42 (because 99^99=0, then 0^42=42),astill holds 42^99. - After
a ^= b:aholds (42^99)^42 = 99 (because 42^42=0, then 0^99=99). Both values are swapped.
This works because XOR is associative, commutative, and self-inverse. It's a puzzle-piece demonstration of XOR's algebraic structure.
a ^ b is bit-by-bit: 1 where the bits differ. It's the "toggle" operator — use it to flip specific bits, find the odd-one-out in a list, swap values, or compute checksums. The three identities a ^ a = 0, a ^ 0 = a, and a ^ b ^ b = a are the foundation of all XOR tricks.
Frequently Asked Questions
1. What's the difference between ^ and !=?
^ is bitwise XOR — it compares integers bit by bit and produces an integer. != is logical inequality — it compares two values and produces 0 or 1. For example, 5 ^ 3 = 6 (bitwise), but 5 != 3 = 1 (logical). Use ^ when you want to manipulate individual bits, and != when you want a boolean answer.
2. How do I toggle a specific bit using XOR?
Use n ^ (1 << k). This flips bit k: if it was 0, it becomes 1; if it was 1, it becomes 0. All other bits are unchanged. For example, to toggle bit 3: n = n ^ (1 << 3) or equivalently n ^= (1 << 3). XOR is the only bitwise operator that toggles — AND can only clear, OR can only set, but XOR can flip either direction.
3. How does XOR find the odd-one-out in an array?
If every element in an array appears exactly twice except for one element that appears once, then XORing all elements together yields the unique element. This works because a ^ a = 0 — every pair cancels out, leaving only the unpaired element. For example, in [3, 5, 3, 7, 5], the XOR is 3^5^3^7^5 = (3^3)^(5^5)^7 = 0^0^7 = 7. This is a common interview question and one of the most elegant applications of XOR.
4. Is the XOR swap trick still useful?
Not really — modern compilers optimize a temp-variable swap (temp = a; a = b; b = temp;) into the same machine code, and the temp-version is clearer and free of subtle pitfalls (e.g., if a and b refer to the same memory location, the XOR swap can zero out the value). The XOR swap is a puzzle piece — interesting for understanding XOR's properties, but rarely used in production code. Use the temp-variable swap in real programs.
5. Can XOR be used for encryption?
Yes — a simple XOR cipher: ciphertext = plaintext ^ key; plaintext = ciphertext ^ key;. XORing with the same key twice returns the original. This is the basis of the one-time pad, which is theoretically unbreakable if the key is truly random, as long as the message, and never reused. In practice, XOR ciphers are trivially broken unless the key is at least as long as the message and truly random (which makes it a one-time pad, not just a "XOR cipher"). For real encryption, use AES or ChaCha20, not raw XOR.
💡 Tip: once this works, try these classic XOR applications: (a) find the unique element in an array where all others appear in pairs, (b) toggle a bit with n ^ (1 << k), (c) swap two values with XOR (and compare to the temp-variable version), (d) implement a simple XOR cipher, (e) compute parity (XOR all bits of a number). Each is a small extension of the same operator.