5

When given two boolean arguments, the ^ operator performs exclusive or, e.g.

true ^ true == false
true ^ false == true
false ^ true == true
false ^ false == false

When given two numeric arguments, it does something, but I've no idea what. At first I thought it was modular division because

(5 ^ 5) == 0

However

(10 ^ 4) == 14

So it's not modular division, is it some kind of bit-shifting?

Dónal
  • 181,534
  • 169
  • 555
  • 808
  • It's bitwise exclusive or, same as Java http://stackoverflow.com/questions/460542/operator-in-java – Rag Aug 17 '11 at 15:04

1 Answers1

12

^ does the same thing as it does in Java and most other languages:

It's a bitwise exclusive OR (short: bitwise XOR)

This means that for every bit in the binary representation of the two numbers the resulting bit in the output will be the bit_in_first_value ^ bit_in_second_value.

Joachim Sauer
  • 291,719
  • 55
  • 540
  • 600
  • 1
    Indeed, to my knowledge all langauges strongly derived from C have this prescribed behavior of their XOR operators. E.G. `perl -le 'print(10 ^ 4)'` prints out 14. Groovy and Perl occupy a similar ecological nice, so much so that [Groovy’s version](http://pleac.sourceforge.net/pleac_groovy/index.html) was the first out of dozens of languages whose translation of the *Perl Cookbook* is complete in the [PLEAC — Programming Language Examples Alike Cookbook](http://pleac.sourceforge.net/) repository on Sourceforge. OCaml was the second. Python is at 85% and Ruby at only 65%. Groovy is easy and fun. – tchrist Aug 17 '11 at 15:12