Operators Assignment 8 — Bitwise XOR on Two Numbers Using the '^' Operator
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program: Perform Bitwise XOR on Two Numbers Using the '^' Operator

📑 On this page:
  • The bitwise XOR operator
  • Truth table
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • 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, otherwise 1
  • 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 bit k.
  • 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.
💡 In one line: 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.
Bitwise XOR in C — comparing bits of two integers with the ^ operator, showing the binary result.

Truth table

For each pair of bits, the XOR result is:

Bit a Bit b a ^ b
000
011
101
110

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:

12 = 1100 (binary) 10 = 1010 (binary) ───────────── 12^10 = 0110 (binary) = 6 (decimal)

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 bit k. 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 — returns a, 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: a holds 42^99, b still holds 99.
  • After b ^= a: b holds 99^(42^99) = 42 (because 99^99=0, then 0^42=42), a still holds 42^99.
  • After a ^= b: a holds (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.

🎯 Key idea: 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.

📖 Related Tutorials

  • Previous: Bitwise OR on Two Numbers Using '|'
  • Next: Bitwise Left Shift Using '<<'
  • Toggle a Particular Bit Using XOR
  • Swap Two Numbers Without a Temp Variable
  • Bitwise Operators in C — Full Tutorial
  • All 15 Operator Assignments in C
  • Operators FAQ

Previous Topic: -->> 7. Bitwise OR on Two Numbers Using the '|' Operator   ||   Next Topic: -->> 9. Bitwise Left Shift on a Number Using the '<<' Operator


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.