Swap Two variable using Bit Manipulation

Swapping two numbers using bit manipulation involves a technique that makes use of XOR (^) operator. The XOR operator has a unique property where if you XOR any number with itself, the result is 0, and if you XOR any number with 0, the result is the number itself. This property allows swapping without a temporary variable. Here’s how it works:

Let’s say we have two variables a and b and we want to swap their values without using a temporary variable.

  1. First, we XOR a and b and store the result back in a. After this operation, a contains the result of a XOR b.
  2. Then, we XOR b with the new a (which is a XOR b). Since XORing b with a XOR b cancels out b, we are left with just a, so now b contains the original value of a.
  3. Lastly, we XOR a (which is still a XOR b) with the new b (which now holds the original value of a). This cancels out the original a from a XOR b, leaving us with just b, so now a contains the original value of b.
Kotlin
fun main() {
    var a = 5 // Example value for a
    var b = 7 // Example value for b

    println("Before swap: a = $a, b = $b")

    // Step 1: XOR a and b, store the result in a
    a = a xor b

    // Step 2: XOR the new a (which is a xor b) with b, store the result in b
    b = a xor b

    // Step 3: XOR the new b (which now contains the original value of a) with the new a (a xor b), store the result in a
    a = a xor b

    println("After swap: a = $a, b = $b")
}

Explanation:

  1. a = a xor b: This line XORs a and b and stores the result back in a. The XOR operation produces a unique combination of bits from a and b that, when XOR’d with either a or b again, can produce the other value.
  2. b = a xor b: Now that a contains a xor b, XORing it with b effectively “cancels out” the bits of b (because b xor b = 0 and a xor 0 = a), leaving the original value of a, which is then stored in b.
  3. a = a xor b: At this point, b holds the original value of a, and a holds a xor b. XORing these gives us the original value of b, which is stored in a.

The key to understanding this method is recognizing the properties of the XOR operation. XORing two identical numbers results in 0, and XORing a number with 0 results in the original number. These properties allow the swap to happen without a temporary variable.

Leave a Comment