Java and python ^ operator

java, operators, python

Solution

This is a bitwise operation, and thus it operates on the binary bits of your numbers. 6 is `110` in binary form. 5 is `101` in binary form.

110
101
=== (^ xor)
011

`011` is 3 in binary.

Read up on https://en.wikipedia.org/wiki/Exclusive_or

Problem

For a CompSci class, we were reviewing the Java Math class. Being the foolish programmer that I am, I tried using the ^ operator instead of the Math.pow function. Surprise, Surprise, it did not work. But, what Java spit out, is my question. I am trying to figure out the operation that is being done with the numbers. You can see what I am talking about below. ``` System.out.println(5^1); System.out.println(5^2); System.out.println(5^3); System.out.println(5^4); System.out.println(5^5); System.out.println(5^6); System.out.println(5^7); System.out.println(5^8); System.out.println(5^9); ``` Running the above, I get the following: ``` 4 7 6 1 0 3 2 13 12 ``` The same thing happens when I do the equivalent in Python (`print 5^1`, etc...). The Java API doc says that the ^ is a "bitwise exclusive OR", but that still does not help with how have gets 6 from 5 and 3. Could someone explain why this is happening?

Original source