0
0
CHow-ToBeginner · 3 min read

How to Use Bitwise XOR Operator in C: Syntax and Examples

In C, the bitwise XOR operator is ^. It compares each bit of two integers and returns 1 if the bits are different, otherwise 0. Use it like result = a ^ b; to get the XOR of a and b.
📐

Syntax

The bitwise XOR operator in C is ^. It takes two integer operands and compares their bits one by one.

  • Operands: Two integers (int, char, etc.)
  • Operator: ^ (caret symbol)
  • Result: A new integer where each bit is 1 if the bits differ, 0 if they are the same
c
result = a ^ b;
💻

Example

This example shows how to use the bitwise XOR operator to compare two numbers and print the result.

c
#include <stdio.h>

int main() {
    int a = 12;  // binary: 1100
    int b = 10;  // binary: 1010
    int result = a ^ b;  // XOR operation

    printf("%d ^ %d = %d\n", a, b, result);
    return 0;
}
Output
12 ^ 10 = 6
⚠️

Common Pitfalls

Some common mistakes when using bitwise XOR in C include:

  • Using ^ instead of logical XOR (which C does not have as an operator).
  • Confusing bitwise XOR with logical operators like && or ||.
  • Applying XOR to non-integer types without casting.

Remember, ^ works on bits, not on boolean logic.

c
#include <stdio.h>

int main() {
    int a = 5;  // binary: 0101
    int b = 3;  // binary: 0011

    // Wrong: trying to use XOR as logical operator (does not exist in C)
    // if (a ^ b) {  // This works but means bitwise XOR, not logical XOR
    //     printf("Bitwise XOR is non-zero\n");
    // }

    // Right: use bitwise XOR explicitly
    int result = a ^ b;
    printf("%d ^ %d = %d\n", a, b, result);

    return 0;
}
Output
5 ^ 3 = 6
📊

Quick Reference

Here is a quick summary of the bitwise XOR operator in C:

ConceptDescription
Operator symbol^
OperandsTwo integers
OperationReturns 1 for bits that differ, 0 for bits that are the same
Example5 ^ 3 = 6 (0101 ^ 0011 = 0110)
Use caseToggle bits, simple encryption, parity checks

Key Takeaways

Use the ^ operator to perform bitwise XOR on two integers in C.
Bitwise XOR returns 1 for bits that differ and 0 for bits that are the same.
Do not confuse bitwise XOR with logical operators; C has no logical XOR operator.
Bitwise XOR is useful for toggling bits and simple data manipulation.
Always apply bitwise XOR to integer types for correct results.