Search code examples
c#bit-manipulationxor

Inverse of XOR-Operation


I do the following:

public static byte Merge(this byte b1, byte b2) {
    return (byte)(b1 ^ b2);
}

so I can call:

byteVar = byteVar1.Merge(byteVar2);

Now, I am searching for the inversion of this. I should implement an Unmerge-Method for calling:

byteVar3 = byteVar.Unmerge(byteVar2);

byteVar3 should now be the same as byteVar1.

I have tried:

public static byte Unmerge(this byte b1, byte b2) {
    return (byte)(b1 & ~b2);
}

But it doesn't work correct.


Solution

  • XOR is a self-inverse - so you can just use:

    byteVar3 = byteVar.Merge(byteVar2);
    

    (I'm not sure that "merge" is a particularly good name here, mind you... you've just got an XOR operation. It's not even clear why you'd want a separate method for it.)