In this article, we will write a C program to check if two numbers are equal or not using the bitwise XOR operator.
The program takes two numbers from the user as input and prints on the screen if they are equal or not.
Sample Input:
Enter First Number: 10
Enter Second Number: 20
Output:
Numbers are not equal
The basic idea behind checking if two numbers are equal or not using the bitwise XOR(^) is that if two numbers are equal, their bitwise XOR result will always be zero.
The output of XOR is true(1) only when the two input bits are different. If both bits are same(either 0 or 1), their XOR is always false(0). See the truth table below:
Input1 | Input2 | Output(XOR) |
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
From the above truth table, you can see that if two input bits are same, their XOR will always be zero. This means if we have two equal numbers and we perform the bitwise XOR operation on them, the result will always be zero.

As you can see from the above image, the bitwise XOR of 2^2 is zero whereas the bitwise XOR of 2^3 is non-zero.
The following C program shows how you can use the bitwise XOR(^) operator to check if two numbers are equal or not:
// C program to check if two numbers are equal // using bitwise XOR(^) operator #include <stdio.h> int main() { int num1, num2, res; printf("Enter First Number: "); scanf("%d", &num1); printf("Enter Second Number: "); scanf("%d", &num2); // Peform bitwise XOR res = num1 ^ num2; // Check if XOR is zero if (res == 0) { printf("Both numbers are equal."); } else { printf("Numbers are not equal"); } return 0; }
Output:
Enter First Number: 10 Enter Second Number: 20 Numbers are not equal
Code Explanation:
- The program takes two inputs from the user and stores them in the
num1
andnum2
variables respectively. - To check if two numbers are equal or not, we performed the bitwise XOR(^) on them. If both numbers are equal, their bitwise XOR(^) will be zero, otherwise, it will be a non-zero value.
- If the result of XOR is zero, the
if
block’s code is executed, otherwise, theelse
block’s code is executed. - Finally, the output is printed on the screen using the printf() function.
Thanks for reading.