C program to swap two numbers using bitwise operator

Write a C program to input any two numbers from user and swap values of both numbers using bitwise operator. How to swap two number using bitwise operator in C programming.

Example

Input

Input first number: 22
Input second number: 65

Output

First number after swapping: 65
Second number after swapping: 22

Required knowledge

Basic C programming, Bitwise operator

Logic to swap two numbers using bitwise operator

There are tons of discussions going around the internet about swapping two numbers without using temporary variable (third variable). You can perform swapping of two numbers using bitwise XOR ^ operator. Bitwise XOR operator evaluates each bit of the result to 1 if each corresponding bits of the two operands differ else evaluates to 0. Apart from this bitwise operator has an special property which is explained in below example.

Suppose two integer values a and b
Let's suppose x = a ^ b
Then again x ^ b will evaluate to a and x ^ a will evaluate to b.

Swapping two numbers using bitwise operator

Program to swap two numbers

/**
 * C program to swap two numbers using bitwise operator
 */

#include <stdio.h>

int main()
{
    int num1, num2;

    // Input two numbers from user
    printf("Enter any two numbers: ");
    scanf("%d%d", &num1, &num2);

    printf("Original value of num1 = %d\n", num1);
    printf("Original value of num2 = %d\n", num2);

    num1 ^= num2;
    num2 ^= num1;
    num1 ^= num2;

    printf("Num1 after swapping = %d\n", num1);
    printf("Num2 after swapping = %d\n", num2);

    return 0;
}

Output

Enter any two numbers: 22
65
Original value of num1 = 22
Original value of num2 = 65
Num1 after swapping = 65
Num2 after swapping = 22

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>