Search code examples
c#binarybitwise-operatorsxor

XOR Operator - How does it work?


Can you please explain me in plain English what is the XOR (^) operator and what it does in the following code:

public int GetHashCode(Box bx)
{
    int hCode = bx.Height ^ bx.Length ^ bx.Width;
    return hCode.GetHashCode();
} 

Solution

  • XOR stands for exclusive or. It ensures that either A or B is true but never both. In this case we're doing a bitwise operation so you can make a nice little graph of the outcomes, they are as follows;

    0 ^ 1 = 1
    1 ^ 1 = 0
    1 ^ 0 = 1
    0 ^ 0 = 0
    

    Since you're applying it to integers the above outcomes are applied to each bit in the operands. So lets just say you have the values 1, 2, 3 for height, length, and width respectively.

    You would first have

    0001 ^ 0010 resulting in 0011 then that would be XOR'd into 3 so 0011 ^ 0011 which gives you 0000

    EDIT: supplying the wiki link from the comments to supplement my explanation; http://en.wikipedia.org/wiki/Exclusive_or#Computer_science

    EDIT: Why does 0001 ^ 0010 result in 0011?

    So it's best to do this bit by bit. Think of the operator iterating over the two sets of bits and comparing pairs of them. So in this case lets work from right to left (least significant to most in this case).

    1 ^ 0 = 1 // xxx1
    0 ^ 1 = 1 // xx11
    0 ^ 0 = 0 // x011
    0 ^ 0 = 0 // 0011  - end of input
    

    so piecing that back together you get 0011. Basically, take each pair of inputs and reference the truth table for the outcome. The comment shows the output with x being a value that has not yet been calculated.

    With regard to collisions, yes, in this case there are plenty of collision. If I said it would be unique that was a poor word choice. What I really mean is that if you have 2, 8, 4 as your values XOR'n them in that order will always produce the same value.