This tutorial teaches you about the Python XOR, a.k.a, bitwise XOR operator. It explains in detail how to calculate the exclusive or (XOR) of two variables in Python.
Understand the Python XOR Operator
XOR operator has a special place in Python. It has several real-time applications like cryptography, bit manipulation, generating checksums, etc. Firstly, let’s understand what it is and how to use it in Python. Later, this tutorial will present examples to help you grasp its usage in Python.
What is XOR in Python?
The XOR operator, denoted by the caret symbol (^), is one of the bitwise operators in Python used for the exclusive OR (XOR) operation. XOR is a logical operation that compares two binary values and returns a new one. The XOR operator plays a crucial role in various programming tasks due to its unique functions.
How XOR Works in Python
The XOR operator works by checking the respective bit of the two integer numbers and produces 1 if the bits are different, otherwise, it returns 0.
To better understand how XOR works, let’s consider two variables, A and B. Both of them store an integer number in binary format.
A = 1100
B = 1010
The XOR operation (A ^ B) compares each pair of bits in A and B:
A: 1 1 0 0
B: 1 0 1 0
--------
A ^ B: 0 1 1 0
The result is 0110, which is the XOR of A and B. To help you easily grasp the concept, here is a simple visual example.
A B Result (A ^ B)
+---+ +---+ +---+
| 1 | XOR | 1 | ---> | 0 |
+---+ +---+ +---+
| 1 | XOR | 0 | ---> | 1 |
+---+ +---+ +---+
| 0 | XOR | 1 | ---> | 1 |
+---+ +---+ +---+
| 0 | XOR | 0 | ---> | 0 |
+---+ +---+ +---+
Let’s also illustrate the XOR operation with Python code:
# XOR operation in Python
A = 10 # binary 1010
B = 6 # binary 0110
result = A ^ B
print(result) # Output: 12 (binary 1100)
By using the Caret “^”
Python uses the caret sign “^” for performing the XOR operation. Below is its syntax.
Basic XOR Syntax
XORresult = operand1 ^ operand2
It takes two integer operands, XOR their binary value bit by bit, and returns the result. See the following example.
# Using XOR with ^
x = 25 # binary 11001
y = 18 # binary 10010
result = x ^ y
print(result) # Output: 11 (binary 01011)
By using the XOR() Function
Python provides a dedicated function operator.xor()
in the operator module for performing the XOR operation. It is slightly a better alternative to the ^ sign in terms of readability.
# Using XOR with operator.xor()
import operator
x = 15 # binary 1111
y = 9 # binary 1001
result = operator.xor(x, y)
print(result) # Output: 6 (binary 0110)
Apart from the integer numbers, xor can also be applied to different data types in Python such as strings and bytes.
How is XOR different from OR and AND?
The XOR, OR, and AND, all of these are bitwise operators in Python. Let’s understand how these operations are different from each other.
XOR Examples in Python
Let’s take a few examples to clarify the use of the XOR operator.
Example1 XOR Boolean Values in Python
We’ll use two boolean variables and apply the XOR operation in four combinations.
a = True
b = True
result1 = a ^ b # False
a = True
b = False
result2 = a ^ b # True
a = False
b = True
result3 = a ^ b # True
a = False
b = False
result4 = a ^ b # False
print("Result 1:", result1) # False
print("Result 2:", result2) # True
print("Result 3:", result3) # True
print("Result 4:", result4) # False
In Python, for arithmetic calculations, the value “True” represents 1, and “False” means 0. So, even though variables a and b are boolean, XOR operates on them like bits and returns the bitwise XOR result.
Example2 XOR with Strings in Python
When working with strings in Python, you might need to apply bitwise operations like XOR. XOR with strings compares the characters of two strings and returns a new string with the corresponding characters XORed together.
Let’s take an example. Suppose we have two strings, “Hello” and “World”. We apply XOR on their characters as follows:
'H' XOR 'W' = '\x0f'
'e' XOR 'o' = '\x1c'
'l' XOR 'r' = '\x1b'
'l' XOR 'l' = '\x1a'
'o' XOR 'd' = '\x1d'
The resulting XORed string is '\x0f\x1c\x1b\x1a\x1d'
. Below is the code using Python XOR with strings.
# XOR with Strings
def xor_strings(str1, str2):
result = ""
for c1, c2 in zip(str1, str2):
result += chr(ord(c1) ^ ord(c2))
return result
# Example:
text1 = "Hello"
text2 = "World"
xor_result = xor_strings(text1, text2)
print(xor_result) # Output: '\x0f\x1c\x1b\x1a\x1d'
Exmaple4 Apply XOR on Lists
For this example, we are using two lists containing boolean values.
# Xor the lists
ls1 = [True, False, True]
ls2 = [True, True, False]
xor_result = [x ^ y for x, y in zip(ls1, ls2)]
print("Result:", xor_result) # Output: [False, True, True]
We have to perform the XOR operation on the corresponding elements of two lists. Hence, we used list comprehension to iterate and the zip function to pair up the adjacent elements. The result of the xor operations was stored in a list as well.
Exmaple4 Apply XOR on Bytes
XOR is easy to use with bytes in Python. It directly compares each bit of the two objects and returns a new byte with the corresponding bits XORed together.
Let’s understand it with an example. Suppose we have two objects of byte type, b'\x10\x20\x30\x40'
and b'\x05\x15\x25\x35'
. We apply XOR on their bytes as follows:
0x10 XOR 0x05 = 0x15
0x20 XOR 0x15 = 0x35
0x30 XOR 0x25 = 0x15
0x40 XOR 0x35 = 0x75
The resulting XORed bytes object is b'\x15\x35\x15\x75'
. The code for the above example is as follows.
# XOR with Bytes
def xor_bytes(bytes1, bytes2):
return bytes(x ^ y for x, y in zip(bytes1, bytes2))
# Example:
data1 = b'\x10\x20\x30\x40'
data2 = b'\x05\x15\x25\x35'
xor_result = xor_bytes(data1, data2)
print(xor_result) # Output: b'\x15\x35\x15\x75'
Applications of XOR in Python
The XOR operator has a variety of applications in Python. Some of the most common applications include:
Data Encryption
XOR is widely used for data encryption. It is a simple and effective encryption method that is relatively easy to implement. XOR encryption works by XORing the data with a secret key.
This means each bit in the data is XORed with the corresponding bit in the key. The result of this XOR operation is a new piece of data that is encrypted. To decrypt the data, the same key is used to XOR the encrypted data. This will result in the original piece of data.
# Data Encryption using XOR
def encrypt_decrypt(data, key):
return ''.join(chr(ord(d) ^ key) for d in data)
message = "Hello, XOR!"
key = 42
encrypted_message = encrypt_decrypt(message, key)
decrypted_message = encrypt_decrypt(encrypted_message, key)
print(encrypted_message) # Output: "\x07\x1c\x15\x15\x1f\x1f\x12\x1b\x15\x14"
print(decrypted_message) # Output: "Hello, XOR!"
Checksum Generation
XOR operator can also be used to produce checksums. It helps in catching errors during network data transfer. In this process, each byte of data is XORed with the previous byte, and the final result is the checksum. Refer to the following Python code:
# Checksum Generation using XOR
def generate_checksum(data):
checksum = 0
for byte in data:
checksum ^= byte
return checksum
data_to_transmit = [0x54, 0x21, 0x87, 0x3F]
checksum = generate_checksum(data_to_transmit)
print(hex(checksum)) # Output: 0xB7
Toggling Bits
XOR is also useful for toggling individual bits in binary numbers, which finds applications in various programming chores. For example, you can toggle a specific bit to 0 or 1 using XOR with an appropriate bitmask.
# Toggling bits using XOR
number = 15 # binary 1111
toggle_mask = 8 # binary 1000 (toggling the 4th bit)
result = number ^ toggle_mask
print(result) # Output: 7 (binary 0111)
Using XOR for Swapping Variables
One of the fascinating applications of XOR is swapping the values of two variables without using a third variable. This bitwise operation works because XORing a number with itself results in 0.
# Swapping variables using XOR
x = 10
y = 20
x ^= y
y ^= x
x ^= y
print(x) # Output: 20
print(y) # Output: 10
XOR as a Hash Function
Another interesting usage of XOR is to use it for hashing. However, it is not always suitable for cryptographic purposes due to its simple nature.
# Simple XOR-based hash function
def simple_hash(data):
hash_value = 0
for byte in data:
hash_value ^= byte
return hash_value
data_to_hash = b"Hello, XOR!"
hashed_value = simple_hash(data_to_hash)
print(hashed_value) # Output: 108
Generating Gray Code
XOR plays a significant role in generating Gray Code, a binary numeral system where two successive values differ in only one-bit position. It is widely used in digital communications and error-correcting codes.
# Generating Gray Code using XOR
def generate_gray_code(n):
return n ^ (n >> 1)
for i in range(16):
print(generate_gray_code(i))
# Output:
# 0 1 3 2 6 7 5 4 12 13 15 14 10 11 9 8
Undoubtedly, the above examples demonstrate numerous applications of XOR in Python. However, there shall be more areas that are beyond the scope of this article. Lastly, it’s essential to explain the distinction between the bitwise XOR and the logical XOR.
Bitwise XOR vs. Logical XOR
It’s important to note the difference between bitwise XOR and logical XOR in Python. While bitwise XOR operates at the bit level, logical XOR operates on Boolean values, returning True if the operands are different and False if they are the same.
# Bitwise XOR vs. Logical XOR
a = True
b = False
bitwise_result = a ^ b
logical_result = a != b
print(bitwise_result) # Output: True
print(logical_result) # Output: True
XOR is a bitwise operator that is essential in Boolean algebra. In binary arithmetic, it behaves as an addition without carry. It is also extensively used in network security protocols, such as IPsec and SSL/TLS. The purpose of XOR in these protocols is to combine cryptographic keys and ensure the confidentiality and authenticity of data during transmission.
Summary
Finally, you have completed the Python XOR tutorial. And, you should now have a good understanding of the XOR operator and its applications. Given that, you can now easily use the XOR operator in your own Python code. As you continue to learn Python, you will likely find many other ways to use the XOR operator. So keep an open mind and experiment with the XOR operator to see what you can create.