Swapping two variables is one of the fundamental operations in programming. Most developers learn the traditional method first — using a temporary variable. However, there is a more efficient and mathematically elegant technique: swap using XOR.
This method allows you to exchange the values of two variables without using any extra memory, relying entirely on the properties of the bitwise XOR operator. It is simple, reliable, and works across all popular programming languages including C, C++, Java, and Python.
Whether you are preparing for technical interviews, studying low-level programming, or improving your understanding of bitwise operations, learning swap using XOR gives you deeper insights into how computers manipulate data at the binary level.ons.
What Is XOR? A Simple Explanation
Before we jump into swapping, let’s understand the hero behind the trick: XOR.
XOR means Exclusive OR.
It behaves like this:
- If two bits are different → output is 1
- If two bits are the same → output is 0
Truth table:
| A | B | A ^ B |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
So XOR literally says:
“I only return 1 if the two bits disagree.”
This weird little behaviour is exactly what makes swap using xor possible.
How XOR Makes Swapping Possible (The Real Magic)
Let’s say:
a = 5
b = 7
Binary:
a = 0101
b = 0111
We perform:
a = a ^ bb = a ^ ba = a ^ b
Let’s break it down.
Step 1
a = a ^ b
Now a becomes some weird mix of both.
Step 2
b = a ^ b
Now b becomes original a.
Step 3
a = a ^ b
Now a becomes original b.
No temp variable.
Just pure bitwise logic.
This method is also called:
- xor swap algorithm
- swap using bitwise xor
- swap two numbers using bitwise xor operator
- swap with xor
- xor to swap two variables
- swap two values xor
Everything means the same technique.
Why XOR Swap Works?
Because XOR has two beautiful properties:
Rule 1
x ^ x = 0
Rule 2
x ^ 0 = x
Rule 3
x ^ y ^ y = x
This third rule is the secret behind the algorithm.
Basic Example of swap using xor
Let’s take:
a = 10
b = 20
Perform:
a = a ^ b
b = a ^ b
a = a ^ b
Result?
a = 20
b = 10
Clean, fast, no memory required.
This is the essence of swap 2 numbers using xor.
Swap Using XOR in C (swap using xor in c)
#include <stdio.h>
int main() {
int a = 5, b = 7;
printf("Before swap: a=%d, b=%d\n", a, b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("After swap: a=%d, b=%d\n", a, b);
return 0;
}
Swap Using XOR in C++ (swap using xor in cpp)
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 20;
cout << "Before swap: a=" << a << " b=" << b << endl;
a = a ^ b;
b = a ^ b;
a = a ^ b;
cout << "After swap: a=" << a << " b=" << b << endl;
return 0;
}
Swap Using XOR in Java (swap using xor java)
public class Main {
public static void main(String[] args) {
int a = 15, b = 25;
System.out.println("Before swap: a=" + a + ", b=" + b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("After swap: a=" + a + ", b=" + b);
}
}
Swap Using XOR in Python (swap using xor in python)
a = 8
b = 12
print("Before swap:", a, b)
a = a ^ b
b = a ^ b
a = a ^ b
print("After swap:", a, b)
Write a Program to Swap Two Numbers Using Bitwise XOR (General Pattern)
a = a ^ b
b = a ^ b
a = a ^ b
Works in all languages.
Understanding XOR Swap at Binary Level
Let’s go deeper.
Imagine:
a = 13 → 1101
b = 9 → 1001
Step 1
a = a ^ b
1101
1001
---- XOR
0100 (a becomes 4)
Step 2
b = a ^ b
0100
1001
---- XOR
1101 (b becomes 13)
Step 3
a = a ^ b
0100
1101
---- XOR
1001 (a becomes 9)
Swap done.
Swap Bytes Using XOR
This is commonly used in low-level programming:
unsigned char x = 0xAB;
unsigned char y = 0xCD;
x ^= y;
y ^= x;
x ^= y;
Now x=CD and y=AB.
Useful in:
- Embedded systems
- Compiler optimization
- Cryptography
- System programming
- Memory manipulation
Swap a and b Using XOR
Let’s take:
a = 3
b = 4
After performing XOR swap:
a = 4
b = 3
This satisfies:
- swap a and b using xor
- xor to swap two variables
- swap two values xor
- swap variables with xor
Where XOR Swap Is Used in Real Life?
Most modern compilers optimize swaps easily, so XOR is rarely used in normal application code. But XOR swap is useful:
- In interview coding rounds
- In extremely tight memory environments
- When working inside registers
- In embedded systems
- In microcontroller code
- In cryptographic functions
- When swapping bytes in buffers
When NOT to Use XOR Swap
Even though this technique is cool, it is NOT always optimal.
Case 1: If a and b refer to the same memory location
a = a ^ a → becomes zero → data loss
Case 2: Harder to read than temp-variable swap
temp = a; a = b; b = temp;
is easier to understand.
Case 3: Modern compilers handle temp-swap better
Optimization makes XOR swap unnecessary.
Interview Tips: How to Explain XOR Swap
Interviewers often ask:
- How to swap using xor?
- How to swap two numbers using xor?
- Why xor swap algorithm works?
- Can we swap without a temporary variable?
Your answer:
“Yes, we can swap two numbers using XOR. The XOR swap algorithm uses three XOR operations. It relies on the identity x ^ y ^ y = x. It saves temporary memory but is less readable and modern compilers optimize normal swaps well.”
Perfect explanation.
Comparison: XOR Swap vs Temp Swap
| Feature | XOR Swap | Temp Swap |
|---|---|---|
| Uses extra variable | No | Yes |
| Readability | Low | High |
| Speed | Same on most CPUs | Same |
| Risk | High (if a=b) | Zero |
| Practical use | Rare | Common |
More Swap Examples Using XOR
1. Swap using xor operator in C
a ^= b
b ^= a
a ^= b
2. Swap using xor operator in C++
Same as above.
3. Swap using xor java
Same logic with ^ operator.
4. Swap using xor in python
Python has native tuple swap, but XOR swap still works.
Edge Cases in XOR Swap
1. Swapping same variables
a = a ^ a = 0
Data destroyed.
2. Floating-point swap
Does NOT work. XOR is for integers.
3. Boolean swap
Works but pointless.
Full Example: swap two numbers using xor in C++
int a = 100;
int b = 200;
a = a ^ b;
b = a ^ b;
a = a ^ b;
Full Example: swapping of two numbers using xor in C
int a = 44, b = 99;
a ^= b;
b ^= a;
a ^= b;
Full Example: swap two numbers using xor in python
a, b = 4, 5
a = a ^ b
b = a ^ b
a = a ^ b
Is XOR Swap Faster Than Normal Swap?
Honestly? No.
Modern CPUs use registers to optimize swaps. Compilers often convert:
temp = a;
a = b;
b = temp;
into register operations faster than XOR.
So XOR swap is just a cool trick, not a performance hack.
Advantages of XOR Swap
- Saves memory (no temp variable)
- Works in all languages
- Fun interview trick
- Makes you understand bitwise logic deeper
Disadvantages of XOR Swap
- Harder to read
- Dangerous when both variables refer to same memory
- Slower on some architectures
- Not suitable for floating values
- Compilers already optimize temp-swaps
Real-World Usage of XOR Swap
- Microcontrollers
- Kernel-level code
- Cryptography
- Data compression
- Embedded system optimization
- Low-level audio/video DSP
Summary
Here’s the simplest summary:
XOR swap is a clever way to swap two integers without using a temporary variable. It relies on XOR properties. It works, but it is rarely used in real production code due to readability and optimization issues.
FAQ
1. What is swap using XOR?
A method to swap two integers without using a temporary variable using bitwise XOR.
2. How to swap two numbers using XOR?
Use three XOR operations:a = a ^ b; b = a ^ b; a = a ^ b;
3. Why does XOR swap algorithm work?
Because XOR is reversible: x ^ y ^ y = x.
4. Can swap using XOR be written in C?
Yes, and it is commonly asked in interviews.
5. Is XOR swap faster?
No. Modern CPUs optimize regular swaps better.
6. Can swap using XOR be used in Python?
Yes, but Python’s a, b = b, a is better.
7. Is it safe to use XOR swap?
Not completely. If a and b refer to same memory, data becomes zero.
8. Can XOR swap handle floats?
No. Only integers.
9. Should I use XOR swap in production code?
No. It’s mainly educational or for interviews.
10. Is XOR swap used in embedded systems?
Yes, sometimes, especially in memory-tight environments.
11. Can I swap bytes using XOR?
Yes. It is used in byte-level optimizations.
12. Is XOR swap useful in competitive programming?
Sometimes, but readability matters more.
Conclusion
Swapping values is one of the first things we learn in programming. But swap using XOR teaches you something deeper — how computers think in bits.
It’s not just a trick to avoid using a temporary variable.
It’s a doorway to understanding bitwise operations, CPU behavior, and low-level programming.
Even though we don’t use XOR swap much in real-world application code, it remains one of the coolest concepts every programmer should know.
Now you know:
- How XOR works
- How to perform variable swap using xor
- How to swap two numbers using xor in C, C++, Java, Python
- How xor swap algorithm actually functions
- When to use it
- When NOT to use it
- Why understanding bits matters
And most importantly…
You now fully understand the secret behind one of the oldest programming tricks ever invented.
If someone now asks you,
“Do you know how to swap without a temporary variable?”
just smile and say:
“Yes , using XOR.”
Mr. Raj Kumar is a highly experienced Technical Content Engineer with 7 years of dedicated expertise in the intricate field of embedded systems. At Embedded Prep, Raj is at the forefront of creating and curating high-quality technical content designed to educate and empower aspiring and seasoned professionals in the embedded domain.
Throughout his career, Raj has honed a unique skill set that bridges the gap between deep technical understanding and effective communication. His work encompasses a wide range of educational materials, including in-depth tutorials, practical guides, course modules, and insightful articles focused on embedded hardware and software solutions. He possesses a strong grasp of embedded architectures, microcontrollers, real-time operating systems (RTOS), firmware development, and various communication protocols relevant to the embedded industry.
Raj is adept at collaborating closely with subject matter experts, engineers, and instructional designers to ensure the accuracy, completeness, and pedagogical effectiveness of the content. His meticulous attention to detail and commitment to clarity are instrumental in transforming complex embedded concepts into easily digestible and engaging learning experiences. At Embedded Prep, he plays a crucial role in building a robust knowledge base that helps learners master the complexities of embedded technologies.
