Search code examples
pythonbinary-operators

Is there any XOR bit reduction operand or function?


Is there any XOR bit reduction operand or function in python? I have no problem to write it by yourself, but there's no reason to write it in every script if there's already built-in.

r=x&1
for i in xrange(1,63):
    r=r^((x>>i)&1)

Solution

  • this doesn't answer your question but that code is the same as:

    def parity(x):
        k = 0
        d = x
        while d != 0:
            k = k + 1
            d = d & (d - 1)
        return k % 2
    

    which has the benefit of not depending on the bit length of the number; and is faster (e.g. on 2**62 yours takes 46.6 usec and this takes 3.02 usec) because the loop depends on the number of ones (i.e. the population count) in the number not the number of bits.