Search code examples
pythonbitparity

Parity of integer with arbitrary bits in python


Lot of solutions suggest using xor with right shift, as described here https://www.geeksforgeeks.org/finding-the-parity-of-a-number-efficiently/

def findParity(x):
    x = x ^ (x >> 16); 
    x = x ^ (x >> 8); 
    x = x ^ (x >> 4);
    x = x ^ (x >> 2); 
    x = x ^ (x >> 1); 
    return x & 1; 

But they assume 32 or 64 bit or some 2^n bits integer. In python integer could have any number of bits. For instance i = 7, has only 3 bits.

i = 7
print(len(bin(i)) - 2)

Any suggestions on how to calculate parity using xor and right shift for arbitrary number of bits ?


Solution

  • You can use a loop to dynamically change the length of the parity check:

    def parity(num):
        length = math.ceil(math.log2(math.ceil(math.log2(num)+1)))
        for i in range(length-1, -1, -1):
            print(2**i)
            num^=(num >> (2**i))
        return num&1
    

    You will need to use log twice because you first have to find the length of the number then you need log that many operations.