[英]Complement of XOR
What is the most efficient algorithm for finding ~A XOR B? 查找〜A XOR B的最有效算法是什么? (Note that ~ is the complement function, done by reversing each 1 bit into 0 and each 0 into 1 bit, and XOR is the exclusive or function)
(请注意,〜是补码功能,通过将每个1位转换为0并将每个0转换为1位来完成,而XOR是互斥或函数)
For example, ~4 XOR 6 = ~010 = 101 = 5 and ~6 XOR 9 = ~1111 = 0 例如,〜4 XOR 6 =〜010 = 101 = 5和〜6 XOR 9 =〜1111 = 0
Here's an answer that takes into account the number of bits needed to store your integers: 这是一个考虑到存储整数所需位数的答案:
def xnor(a, b):
length = max(a.bit_length(), b.bit_length())
return (~a ^ b) & ((1 << length) - 1)
I can't think of a situation where this is better than just ~a ^ b
however. 我想不出这比〜a
~a ^ b
更好的情况。 And it almost certainly makes no sense for negative numbers. 对于负数几乎毫无疑问。
The only problem here is that ~
returns a negative number for a positive input, and you want a positive result limited to the significant bits represented in the inputs. 唯一的问题是
~
为正输入返回一个负数,而您希望将正结果限制为输入中表示的有效位。
Here's a function that can generate a mask of bits that are needed in the result: 这是一个可以生成结果中所需位的掩码的函数:
def mask(n):
n = abs(n)
shift = 1
while n & (n + 1) != 0:
n |= n >> shift
shift *= 2
return n
And here's how to use it: 以及使用方法:
print (~a ^ b) & mask(a | b)
You can simply use ==. 您可以简单地使用==。
A XNOR B is same as == operator because: XNOR B与==运算符相同,因为:
AB NXOR AB NXOR
FFT FFT
FTF FTF
TFF TFF
TTT TTT
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.