Use ^
operator in Python to get XOR int. As XOR is a bitwise operator, it will compare bits of both integers bit by bit after converting them into binary numbers.
The truth table for XOR (binary)
A | B | A⊕B |
---|---|---|
1 | 1 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
0 | 0 | 0 |
Python XOR int
Simple example code.
# Initializing two integers a and b
a = 10
b = 30
# Finding XOR of a and b using ^ operator
c = a ^ b
# Printing the XOR value
print(a, "XOR", b, "=", c)
Output:
XOR(a,b) for integers
def XOR(a,b):
return a ^ b
nbr1 = 67
nbr2 = 73
print (XOR(nbr1, nbr2))
a = 5
b = 3
result = a ^ b
print(result) # Output: 6
In this example, the binary representation of 5
is 101
, and the binary representation of 3
is 011
. Performing a bitwise XOR operation on these binary numbers yields 110
, which is 6
in decimal.
You can use the ^
operator to perform XOR operations on integers in Python.
Do comment if you have any doubts or suggestions on this Python xor topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.