Thursday 2 September 2010

Logical XOR

Flash doesn't have a logical XOR, only a bitwise XOR. That means that you can only do bitwise operations, or swap number and attribute the result to a variable.

Well I needed a Boolean XOR, like the one with Truth Tables that we know from logical programming. Well this little function takes care of this:

public function xor(lhs:Boolean, rhs:Boolean):Boolean {


return !( lhs && rhs ) && ( lhs || rhs );

}



Cheers,
Leonel

5 comments:

  1. I believe that a simple != would work quite well as a boolean XOR :).

    (however, I noticed that seconds after I happily googled for the `xor` operator in AS3 and found your blog :))

    ReplyDelete
  2. xor bitwise operator : '^'. return a^b
    for booleans : return Boolean(int(a) ^ int(b));

    Yorg (www.yorgsite.fr)

    ReplyDelete
  3. A quick benchmark test finds gilles snippet to be a bit faster.

    I thought the casting would make it slower. But looks like it makes up for it with it's minimal amount of comparisons.

    ReplyDelete
  4. Thank you guys... At the time I had to search for a way of doing this, to help a friend, but never really needed it.
    Since AS3 doesn't have a logical XOR method, this is was what I have found. I'm glad you're contributing to make this simpler, logical and faster... Thanks!

    ReplyDelete
  5. Leonel:
    As pointed out by Tomasz said, AS3 *DOES* have a logical XOR method, and it's !=

    true != true returns false
    true != false returns true
    false!= true returns true
    false!= false returns false

    ReplyDelete