简体   繁体   中英

Complement of XOR

What is the most efficient algorithm for finding ~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)

For example, ~4 XOR 6 = ~010 = 101 = 5 and ~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. 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:

AB NXOR
FFT
FTF
TFF
TTT

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM