The XOR swap algorithm uses three XOR (exclusive OR) operations to swap the
values of two variables, a and b. Here’s the step-by-step process:
- Initial Values:
- Let
aandbbe the two variables you want to swap. - Example:
a = 5(binary0101),b = 3(binary0011).
- Let
- First XOR Operation:
a = a ^ b- This step stores the XOR of
aandbina. - Example:
a = 5 ^ 3results ina = 6(binary0110).
- Second XOR Operation:
b = a ^ b- This step updates
bto the original value ofa. - Example:
b = 6 ^ 3results inb = 5(binary0101).
- Third XOR Operation:
a = a ^ b- This step updates
ato the original value ofb. - Example:
a = 6 ^ 5results ina = 3(binary0011).
After these three operations, the values of a and b are swapped.
Bytes