say we have this number 101001110110010
is this the correct way to calculate the parity using XOR:
10 10 01 11 01 10 01 0
1 1 1 0 1 1 1 0
0 1 0
1
1 1
0
say we have this number 101001110110010
is this the correct way to calculate the parity using XOR:
10 10 01 11 01 10 01 0
1 1 1 0 1 1 1 0
0 1 0
1
1 1
0
As an alternative to XORing every bit one by one, we can rely on the ability of a computer to XOR larger integers together. The parity of a large number that consists of two halves H and L, can be computed as the parity of H^L
. That definition gives a (tail)recursive algorithm which halves the size the number at every step, and thus has a logarithmic call depth. It can be implemented iteratively, for example:
def parity(x):
shiftamount = 1
while x >> shiftamount:
x ^= x >> shiftamount
shiftamount <<= 1
return x & 1
i ended up answering my own question, this method is in fact correct, and i'm using it in a linear cryptanalysis implementation in python.
basically, to calculate the parity of a number using XOR, just take each couple of 2 bits and Xor them together, keep doing that until you're left with one number.
here's the implementation if you need it
def FindParity(value):
parity = 0
while value > 0:
extractedValue = value % 2
value //= 2
parity = parity ^ extractedValue
return parity
this function just takes a number and does what i'm doing manually in my question.