[英]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/许多解决方案建议使用带有右移的异或,如下所述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.但他们假设 32 或 64 位或一些 2^n 位整数。 In python integer could have any number of bits.
在 python 中整数可以有任意数量的位。 For instance i = 7, has only 3 bits.
例如 i = 7,只有 3 位。
i = 7
print(len(bin(i)) - 2)
Any suggestions on how to calculate parity using xor and right shift for arbitrary number of bits ?关于如何使用 xor 和右移任意位数计算奇偶校验的任何建议?
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.您将需要使用
log
两次,因为您首先必须找到数字的长度,然后您需要log
那么多操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.