Simplify the inverse function Z = X ^ (X << Y)

I had difficulty simplifying the following function in several atomic binary operations, it seems to me that this is possible, but I can’t do this, I have been scratching my head a little for several hours:

public UInt32 reverse_xor_lshift(UInt32 y, Int32 shift)
{
    var x = y & (UInt32)((1 << shift) - 1);

    for (int i = 0; i < (32 - shift); i++) {
        var bit = ((x & (1 << i)) >> i) ^ ((y & (1 << (shift + i))) >> (shift + i));

        x |= (UInt32)(bit << (shift + i));
    }

    return x;
}

what the function does is simply calculate the inverse Z = X ^ (X << Y), in other wordsreverse_xor_lshift(Z, Y) == X

+4
source share
1 answer

You can invert it with a much smaller number of operations, although it is more difficult to understand using the same technique as in the conversion from gray code :

z ^= z << i, i shift .

:

while (i < 32)
    x ^= x << i
    i *= 2

, xor ( ) , "xored in", , "xoring them out". , , . x ^ (x << k) ^ (x << k) ^ (x << 2k) = x ^ (x << 2k), , , , .

+4

Source: https://habr.com/ru/post/1598669/


All Articles