Reputation: 35126
I could not find an XNOR operator to provide this truth table:
a b a XNOR b ---------------- T T T T F F F T F F F T
Is there a specific operator for this? Or I need to use !(A^B)?
Upvotes: 204
Views: 83212
Reputation: 8998
XOR A B
is the same thing as AND (OR A B) (NAND A B)
, or in other words, A
or B
, but not both. XOR A B
is only true when A
and B
are not equal, so it can be also thought of as an inequality check--if XOR A B
is true, then A
and B
must have opposing values (true and false or vice versa).
XNOR
is the exact inverse, and can be thought of as an equality check--if XNOR A B
is true, then A
and B
must have the same value (both false or both true).
However, non-boolean cases present problems, like in this example:
a = 5
b = 1
if (a == b) {
...
}
This will compare false because 5 = 1
is not true. If your intent is to check that both a
and b
are the same in terms of being zero/nonzero, then you could do it like this:
if ((a && b) || (!a && !b)) {
...
}
or alternately
if (!(a || b) && (a && b)) {
...
}
Though this is a really roundabout approach. Remember the intent is to check that both are zero/nonzero. The most direct way to check that would probably be use the Logical NOT operator:
if (!a == !b) {
...
}
Upvotes: 5
Reputation: 1
I there is a few bitwise operations I don't see as conventional in the whole discussion. Even in c, appending or inserting to the end of a string, all familiar in standard IO and math libs. this is where I believe the problem lies with not and Xnor, not familiar with python but I propose the following example
function BitwiseNor(a as integer)
l as string
l=str(a)
s as string
For i=len(l) to 0
s=(str(i)+"="+Bin(i)) //using a string in this example because binary or base 2 numnbers dont exists in language I have used
next i
endfunction s
function BitwiseXNor(a as integer,b as integer)
r as integer
d as integer
c as string
c=str(BitwiseOr(a,b))
r=(val(c,2)) //the number to in this conversion is the base number value
endfunction r
Upvotes: -1
Reputation: 1
You can use ===
operator for XNOR.
Just you need to convert a
and b
to bool.
if (!!a === !!b) {...}
Upvotes: -11
Reputation: 263577
XNOR is simply equality on booleans; use A == B
.
This is an easy thing to miss, since equality isn't commonly applied to booleans. And there are languages where it won't necessarily work. For example, in C, any non-zero scalar value is treated as true, so two "true" values can be unequal. But the question was tagged c#, which has, shall we say, well-behaved booleans.
Note also that this doesn't generalize to bitwise operations, where you want 0x1234 XNOR 0x5678 == 0xFFFFBBB3
(assuming 32 bits). For that, you need to build up from other operations, like ~(A^B)
. (Note: ~
, not !
.)
Upvotes: 341
Reputation: 14654
No, You need to use !(A^B)
Though I suppose you could use operator overloading to make your own XNOR.
Upvotes: 4