XOR problem

Hy!

I understand how working XOR with Boolean type dates, but how can I use integer type?
In C++ all data that !=0 are considered true, but with int type I get the following:

10 XOR 10 --------> FALSE
10 XOR 20 --------> TRUE ; Is any chance to get FALSE too?

I may be wrong, as I don't often use it, but if you are referring to ^ as XOR then it is a BITWISE operator, not a "normal" boolean operator like && (AND) or || (OR).

In binary,
10 is 00001010
20 is 00010100
and bit-by-bit ^ between these would give
00011110
which is non-zero, hence TRUE.

(OK, that's the rough gist - somebody else will have to check my binary and bitwise operations!)

The corresponding bitwise operators for AND and OR are (I think) & and | (that's single characters).
Last edited on
Here's a functional form of XOR which does what you want. Perhaps somebody could do an overloaded-operator version of the same thing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
using namespace std;

template <class T, class U> bool XOR( T a, U b )
{
   return ( a && (!b) ) || ( (!a) && b );
}



// Test it ...

int main()
{
   cout << boolalpha;

   cout << XOR( true , true  ) << endl;
   cout << XOR( false, false ) << endl;
   cout << XOR( true , false ) << endl;
   cout << XOR( false, true  ) << endl;

   cout << XOR( 10, 10 ) << endl;
   cout << XOR( 10, 20 ) << endl;

   cout << XOR( 10, 10.0 ) << endl;
   cout << XOR( 10.0, 20 ) << endl;

   cout << XOR( 10, 0.0 ) << endl;
   cout << XOR( 0, 10.0 ) << endl;
}
Topic archived. No new replies allowed.