user1092472
user1092472

Reputation: 391

Java XNOR operator

I do some research and I wrote some simple programs in java that suits my needs. I used logical operators AND,OR,XOR on integers but I miss XNOR operator. That what I'm looking for is a XNOR operator that behaves just same as others mentioned (could be applied on integers). Is it possible from somebody to write such a class in Java?

Upvotes: 39

Views: 43444

Answers (4)

eboix
eboix

Reputation: 5133

The operator for XNOR is A==B, or !(A^B). This returns a boolean value.

Upvotes: 4

Nick
Nick

Reputation: 61

if (!a ^ b) doSomething();

It gives the same result so you do not have to use brackets.

And I would prefer an XOR gate more since a mistake is likely to be made if you accidentally use a = at somewhere which supposed to be a ==.

if (a = b) doSomething(); // performs like "if (b) doSomething();"

A bitwise version as well.

someInt = ~a ^ b

Upvotes: 4

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

boolean xnor(boolean a, boolean b) {
    return !(a ^ b);
}

or even simpler:

boolean xnor(boolean a, boolean b) {
    return a == b;
}

If you are actually talking about bitwise operators (you say you're operating on int), then you will need a variant of the first snippet:

int xnor(int a, int b) {
    return ~(a ^ b);
}

Upvotes: 87

SLaks
SLaks

Reputation: 887315

The logical XNOR operator is ==.

Do you mean bitwise?

Upvotes: 25

Related Questions