Search code examples
pythonbitbit-shiftxor

Bit shift and XOR function of two ints


I have quite a weird operation in my programme. Given are two numbers a and b in binary. The second number tells how many summands I built, namely the amount of 1s in the number. Their positions (powers of 2) tell how far a gets shifted before getting a new summand.

Example:

    a = 1100101
    b =   10110
 index= 6543210

b has a 1 at the indices 1, 2 and 4 (from right to left), so the summands are (filling with zeros), being shifts of a:

(a << 1), (a << 2), (a << 4)

Those get XORed all together: (a << 1) ^ (a << 2) ^ (a << 4)

Second example:

a = 110101
b =  10101

Result:

(a << 0) ^ (a << 2) ^ (a << 4)

Normally, I would now order a and b such that b is shorter, then for-loop over the indices of b and put shifted summands into an array and go over the array to XOR them in the end.

But isn't there a smoother way for doing that?


Solution

  • Perhaps, Python isn't the best choice for stuff like this.

    res = 0  # this is where the result will be
    while b:
        b, flag = divmod(b, 2)
        res ^= a*flag
        a <<= 1