Swapping two numbers using Bitwise XOR operator is tricky one and it’s generally asked in interviews. There are other two methods also through which you can swap two numbers.
Swap two numbers using third variable
Swap two numbers without using third variable
Swap Two Numbers Using Bitwise XOR Operator
Let’s check how to swap two numbers using XOR operator. Suppose i have two integers x=7 and y=2.
XOR is 1 only if exactly one of its inputs are 1, otherwise it’s 0.
1 2 3 |
x = x ^ y; y = x ^ y; x = x ^ y; |
Convert 7 and 2 into binary number.
x = 0111 and y = 0010
1 2 3 |
x = x ^ y = 0101 // 5 y = x ^ y = 0111 // 6 x = x ^ y = 0010 // 2 |
Final value of x is 2 and y is 7
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <stdio.h> void main(){ int x=7,y=2; x = x ^ y; y = x ^ y; x = x ^ y; printf(" Value of x = %d and y = %d",x,y); } |
PHP Code to Swap Two Numbers Using Bitwise XOR Operator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php $x = 7; $y = 2; // Swap Logic $x = $x ^ $y; $y = $x ^ $y; $x = $x ^ $y; echo "The number after swapping is"; echo "Number x =".$x." and y=".$y; ?> |