Program to Swap Two Numbers Using Bitwise XOR Operator

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.

Convert 7 and 2 into binary number.

x = 0111 and y = 0010

Final value of x is 2 and y is 7

PHP Code to Swap Two Numbers Using Bitwise XOR Operator

More Read on XOR Swap Algorithm

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.