Search code examples
javaalgorithmbitwise-xor

How does Xor work in swapping values?


Here is the original code:

public static String reverseString(String s){       
    if(s == null) return "";        
    char[] rev = s.toCharArray();
    int i = 0, j = s.length() - 1;
    while(i < j) {
        rev[i] ^= rev[j];
        rev[j] ^= rev[i];
        rev[i++] ^= rev[j--];           
    }       
    return String.valueOf(rev); 
}

My question is how does Xor work in swapping character values here, and why is rev[i++]^=rev[j--] needed here?


Solution

  • The code is equivalent to

        rev[i] ^= rev[j];
        rev[j] ^= rev[i];
        rev[i] ^= rev[j];           
        i++;  j--;
    

    The last part is just needed to increment i and decrement j for the next loop iteration.

    As to why x ^= y; y ^= x; x ^= y works to swap the values, I don't know why, but you can see that it works on 1-bit values by look at all four possibilities:

     start   after x^=y  after y^=x   after x^=y
    x    y     x   y       x   y        x   y
    0    0     0   0       0   0        0   0
    0    1     1   1       1   0        1   0
    1    0     1   0       1   1        0   1
    1    1     0   1       0   1        1   1
    

    So you can see that in all cases, the x and y bits are swapped. When the statements are applied to larger integers, the ^ operator works on all bits in parallel, so the end result is that every pair of bits is swapped, i.e. the entire values are swapped.