Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Swapping numbers using bitwise operator in C
Swapping two numbers using bitwise operators in C is an efficient technique that uses the XOR (^) operator to exchange values without requiring additional memory for a temporary variable. This method works by exploiting the property that XORing a number with itself results in zero.
Syntax
a = a ^ b; b = a ^ b; a = a ^ b;
How XOR Swapping Works
The XOR swap algorithm works on the mathematical property that X ^ X = 0 and X ^ 0 = X. When we perform the three XOR operations, the values get exchanged without using extra memory −
Example
Here's a complete program demonstrating XOR swap in C −
#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Before swap: a = %d, b = %d<br>", a, b);
/* XOR swap algorithm */
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("After swap: a = %d, b = %d<br>", a, b);
return 0;
}
Enter two numbers: 24 56 Before swap: a = 24, b = 56 After swap: a = 56, b = 24
Binary Explanation
Let's trace through the binary operations for the values 24 and 56 −
| Step | Operation | Binary Calculation | Result |
|---|---|---|---|
| Initial | a = 24, b = 56 | 011000, 111000 | a = 24, b = 56 |
| 1 | a = a ^ b | 011000 ^ 111000 = 100000 | a = 32, b = 56 |
| 2 | b = a ^ b | 100000 ^ 111000 = 011000 | a = 32, b = 24 |
| 3 | a = a ^ b | 100000 ^ 011000 = 111000 | a = 56, b = 24 |
Key Points
- No temporary variable needed, making it memory efficient
- Works only with integers − cannot be used with floating-point numbers
- Fails if variables point to the same memory location (a and b are the same variable)
- Time complexity: O(1) with three XOR operations
Conclusion
XOR swapping is an elegant technique for exchanging integer values without temporary variables. While useful for understanding bitwise operations, modern compilers often optimize regular swapping just as efficiently.
