0

I have problem with XOR. There is some example. I have this: bool a[4]=[1,0,0,1] and bool b[4]=[0,1,0,1]. I want to create XOR and write into boll xor[4]. I try this,but it does not work. Can you help me with this?

bool xor[4];
   for(int i=0;i<4;i++){
     if((a[i]==0) && (b[i]==0)){
       xor[i]=0;
     }
     else if((a[i]==1) && (b[i]==1)){
       xor[i]=0;
     }
     else if((a[i]==1) && (b[i]==0)){
       xor[i]=1;
     }
     else if((a[i]==0) && (b[i]==1)){
       xor[i]=1;
     }
   }
Natalia
  • 17
  • 2

1 Answers1

0

Maybe something more simple.

int xor(int a, int b)
{
    return (!!a) ^ (!!b);
}

I use binary XOR. But to make sure that vales passed are 0 or 1 I double logically negate the parameters.

Or as Eugene Sh. mentioned

bool xor(int a, int b)
{
    return (!!a) != (!!b);
}

// OR if you want to use xor binary operator

bool xor(int a, int b)
{
    return !!((!!a) ^ (!!b))
}

https://godbolt.org/z/NoCPbu

0___________
  • 60,014
  • 4
  • 34
  • 74
  • "One of A and B is true," is the same thing as, "one of not A and not B is true"; could be simplified. – Neil Feb 28 '20 at 20:14
  • _Eg_ I believe `!!((!!a) ^ (!!b)) == (!!a) ^ (!!b) == !a ^ !b`. – Neil Feb 28 '20 at 21:58
  • @Neil no it is not. Being strict they different types and that was the point of those operations – 0___________ Feb 29 '20 at 01:54
  • Negation is a projection to `{0,1}` in the sense that it's range is idempotent; see [this answer](https://stackoverflow.com/a/3532331/2472827). XOR is [commutative and it's own inverse](https://math.stackexchange.com/questions/961441/xor-is-commutative-associative-and-its-own-inverse-are-there-any-other-such-f). `a ^ b` would give a different answer if `a,b \notin [0,1]`, but I think that my simplifications are general. – Neil Feb 29 '20 at 20:37