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?
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);
}
-
I have tried your answer with int xnor(int a, int b) { return ~(a ^ b); } but it gives false results .For instance 10 NXOR 12 = 9 it is not negative number. – user1092472 Dec 12 '11 at 20:40
-
-
@user1092472: If you only want to perform the operation on a subset of the bits, you will need to perform a mask with
&
. – Oliver Charlesworth Dec 12 '11 at 21:10 -
For XOR or XNOR on two boolean values, can't you just do
if (b1 != b2) //XOR
orif (b1 == b2) //XNOR
? What advantage does doingif (b1 ^ b2) //XOR
orif (!(b1 ^ b2)) //XNOR
give? – ADTC Sep 28 '12 at 6:43 -
The logical XNOR operator is ==
.
Do you mean bitwise?
-
Here is my little program with xor operator. I need the same program with XNOR operator.
code
public class xor { public static void main (String argv[]) { int i=1; for (int j=0;j<100;j++){ int x = ((i) ^ (j)); System.out.print(j); System.out.print(" "); System.out.println(x); }code
– user1092472 Dec 11 '11 at 21:55
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