XOR (Exclusive OR) is a bitwise operation in computer programming that combines two binary inputs in such a way that the output is true (1) if and only if exactly one of the input values is true. In this blog post, we will explore how to perform the XOR operation on two numbers using Python.
Understanding XOR
Before diving into the Python code, let’s understand what XOR does. The XOR operation takes two binary inputs and returns the output according to the following truth table:
Input A | Input B | Output (A XOR B) |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
XOR in Python
Python provides a built-in operator for performing the XOR operation on two numbers. The XOR operator in Python is denoted by the caret symbol (^). Here’s a simple example:
b = 3
result = a ^ b
print(“The XOR of 5 and 3 is:”, result)
In the code above, the numbers 5 and 3 are XORed using the ^ operator, and the result is printed. The output will be: The XOR of 5 and 3 is: 6.
XOR with Binary Numbers
If you want to work directly with binary numbers, you can use the bin() function to convert the integers to binary and the int() function to convert the binary output back to an integer. Here’s an example:
b = 0b011
result = a ^ b
print(“The XOR of 0b101 and 0b011 is:”, bin(result), “or”, int(result))
In this example, the numbers are entered in binary form using the 0b prefix. The output will be: The XOR of 0b101 and 0b011 is: 0b110 or 6.
Conclusion
In this blog post, we learned how to perform the XOR operation on two numbers using Python’s built-in ^ operator. We also explored how to work with binary numbers directly in Python. Now you can easily XOR two numbers in your Python code!