What Does the “^” Operator in Python Do?

Problem scenario
In Python you try operations like these two:

5 ^ 6
9 ^ 10

Both return "3". Why is this?

Solution
The exclusive or (aka XOR) symbol "^" "copies the bit if it is set in one operand but not both." (Taken from https://www.tutorialspoint.com/python/python_basic_operators.htm)

Here are some integers with their binary representation one space away:

3 11

5 101
6 110

9 1001
10 1010

5 is represented as 101. 6 is represented as 110. The 1 is set in the middle and right-most position of the binary values. Thus it returns a 3 which is associated with "11" in binary notation.

7 ^ 8 returns 15. 15 in binary notation is 1111.

7 111
8 1000

If we remember that ^ "copies the bit if it is set in one operand but not both." (taken from https://www.tutorialspoint.com/python/python_basic_operators.htm), we would expect it to return 1111. The integer equivalent of 1111 is "15".

To view more binary equivalents, see this https://www.convertbinary.com/numbers/.

Leave a comment

Your email address will not be published. Required fields are marked *