- Explained Python XOR Operator in Simple Terms
- What are Bitwise Operators?
- Exploring XOR
- Syntax & Example Code
- XOR using the Operator Module
- Finding XOR of 2 Numbers Without Python XOR Operator
- Python XOR Vs. Python OR
- Encryption/Decryption using XOR
- How to Bitwise XOR of Hex Numbers in Python?
- Implementing XOR on all elements in a Python Array
- FAQs on Python XOR Operator
- Conclusion
- Everything about python xor function | Basic to advance [2023]
- What is the xor function in Python?
- Syntax of python xor function
- Example of python xor function
- Python xor between two boolean
- Python xor between two integers
- Python xor between two list
- Python xor between two strings
- Python xor between two hexadecimal values
- XOR in Python using Operator Module
- Conclusion
Explained Python XOR Operator in Simple Terms
All information in computers is stored in a stream of binary digits called bits. All the programs, software, image files, video files are all nothing but ones and zeros. Bitwise operators like Python XOR, AND etc., let you manipulate bits of data at the most intricate level.
What are Bitwise Operators?
Python provides a variety of operators, including arithmetic, logical, and comparison operators. They are functions that utilize a more compact prefix and infix syntax. Unlike the C language, Python doesn’t include increment and decrement operators as bitwise operators.
Here’s a run-down of the available bitwise operators in Python
Operator | Description |
---|---|
& | Bitwise AND |
| | Bitwise OR |
~ | Bitwise NOT |
^ | Bitwise XOR (Exclusive OR) |
>> | Bitwise Right Shift |
Bitwise Left Shift |
Most bitwise operators are binary (takes two operands). However, bitwise NOT is the only unary operator (takes one operand).
Exploring XOR
Make sure to run these programs yourself. Try using our online Python compiler.
Unlike bitwise AND, OR, and NOT, the bitwise XOR operator doesn’t have a logical counterpart in Python.
In a nutshell, it evaluates whether or not two mutually exclusive conditions are met. For example, a person can be either a biological male or a female, but not both at the same time. Similarly, it’s not possible for a person to be neither a biological male nor a female. At least one condition must be satisfied.
Syntax & Example Code
# a and b must be integer objects a = 13 b = 4 print(a ^ b)
Here’s the Truth Table for the XOR operator
XOR using the Operator Module
We can implement the XOR operator using the operator module. It’s part of the Python standard library.
import operator print(operator.xor(10,20)) print(operator.xor(True,True)) print(operator.xor(False,False)) print(operator.xor(False,True)) print(operator.xor(True, False))
Finding XOR of 2 Numbers Without Python XOR Operator
The following program creates a function that mimics Python’s default XOR operator
def XORFunction(x, y): #Initializing resultant variable res = 0 # Assuming provided integers are 32 bit integers for i in range(31, -1, -1): # Find the bits of the provided integers b1 = x & (1enter an integer: 10 enter an integer: 3 XOR of X and Y is 9Python XOR Vs. Python OR
Python XOR | Python OR |
---|---|
Python XOR is, also known as “exclusive or”, compares two binary numbers bitwise if two bits are identical XOR outputs as False. True, and when two bits are different, then XOR outputs as 1. | With the Boolean OR operator, you can connect two Boolean expressions into one compound expression. At least one subexpression must be true for the compound expression to be considered true, and it doesn’t matter which. If both subexpressions are false, then the expression is false. |
It is used to avoid two True or two False conditions. | It is used to find at least one True condition. |
Encryption/Decryption using XOR
XOR Encryption method that allows us to Encrypt string messages that cannot be decrypted using simple brute force (trial and error). It makes use of a Key and Python XOR, which operates on each and every message’s character. Here’s the Python function. It is to be noted that XOR Cipher uses a similar implementation for encryption.
def XORCipher(inpString): # Create a key using any character key = 'V'; # Length of the string to be encrypted length = len(inpString); # XOR operation on every key along with characters of the input string for i in range(length): inpString = (inpString[:i] + chr(ord(inpString[i]) ^ ord(key)) + inpString[i + 1:]); print(inpString[i], end = ""); return inpString; if __name__ == '__main__': sampleString = "Python Pool"; # Encrypting sampleString print("Encrypted String: ", end = ""); sampleString = XORCipher(sampleString); print("\n"); # Decrypt the string print("Decrypted String: ", end = ""); XORCipher(sampleString);
How to Bitwise XOR of Hex Numbers in Python?
A simple way of implementing XOR on Hex numbers is to use the standard XOR (^) Operator and Python’s hex function. Check out the following example.
a = 0x23c4 b = 0x7d21 # Passing the results of the XOR operations into the hex function print(hex(a ^ b))
Implementing XOR on all elements in a Python Array
The following code explains how we can perform XOR operations for elements in an Array.
def XORArray(arr, n): # Resultant variable xor_arr = 0 # Iterating through every element in the array of size n for i in range(n): # Finding XOR for each element xor_arr = xor_arr ^ arr[i] # Return the resultant variable return xor_arr if __name__ == '__main__': myArray = [22,23,24,9,55] n = len(myArray) # Function call print(XORArray(myArray, n))
FAQs on Python XOR Operator
Why were bitwise operations slightly faster than addition/subtraction operations on older microprocessors?
Adders add the low bits and produce a carry and one output bit. As a result, the next two lowest bits are added, and a carry is added, generating another output bit and another carry. This continues. The highest output bit is at the end of a chain. Older processors did these operations step by step, thereby making them slightly slower.
Let’s say you have two String Types, and you want to check if only one of them stands True.
Since you’re working with boolean values bitwise, XOR will not be able to perform its operations on the string types. Therefore, logical XOR will look like this:
def logical_xor(str1, str2):
return bool(str1) ^ bool(str2)
Conclusion
We have discussed Python XOR and how it is different from Python OR. A program demonstrating how the XOR operation works internally has been discussed. XOR provides multiple use cases, whether it may be bitwise or logical, such as Encryption and Decryption of messages. Thereby proving to be one of the interesting bitwise/ logical operators of Python.
Everything about python xor function | Basic to advance [2023]
Python provides many bitwise operators like AND, OR, XOR, etc. In this session, we will learn about the python xor function. so let’s get started.
What is the xor function in Python?
In Python, a bitwise operator is an operator used to perform a bitwise operation on two integer operands. A bitwise operation operates on the individual bits of an integer, rather than on the integer as a whole.
One such bitwise operator is the python XOR function. You can use the ^ operator to perform bitwise XOR operation. For each bit position in the first operand, the bitwise XOR operation compares the corresponding bit in the second operand. If the bits are different, the result bit in that position is set to 1. If the bits are the same, the result bit is set to 0.
Syntax of python xor function
Below is the general syntax of the python xor function.
xor_num = operand1 ^ operand2
The operand can be an integer, string, list or boolean.
Example of python xor function
In this session, we will explore different examples of using the Python xor function.
Python xor between two boolean
In Python, we can use the xor( ^) operator to perform a bitwise XOR operation on two booleans. Note that in Python, the True and False values are treated as 1 and 0, respectively, when used in a bitwise operation.
Therefore, the bitwise XOR of True and True is equivalent to the bitwise XOR of 1 and 1, which is 0 (False). Similarly, the bitwise XOR of True and False is equivalent to the bitwise XOR of 1 and 0, which is 1 (True).
Let’s understand this with the below example:
def xor(a, b): return a ^ b print(xor(True, True)) print(xor(False, False)) print(xor(True, False)) print(xor(False, True))
This function takes two booleans as input and returns the bitwise XOR between them. The above code returns the below output
Python xor between two integers
A user can also use the xor(^) function to perform a bitwise XOR operation on two integers. Below is an example of how you could implement a function to perform a bitwise XOR operation on two integers:
def xor(a, b): return a ^ b print(xor(1, 2)) print(xor(5, 3))
The bitwise XOR of 1 (0001 in binary) and 2 (0010 in binary) is 3 (0011 in binary) because only the first and second bits are different.
Similarly, the bitwise XOR of 5 (0101 in binary) and 3 (0011 in binary) is 6 (0110 in binary), because only the first and third bits are different.
Python xor between two list
The Python xor(^) operator can be used to perform a bitwise XOR operation on the elements of two lists. However, this operation will only work if both lists are of identical length and contain only integers or boolean values.
Below is an example of how you could implement a function to perform a bitwise XOR operation on the elements of two lists in Python:
def xor_lists(l1, l2): result = [] for x1, x2 in zip(l1, l2): result.append(x1 ^ x2) return result print(xor_lists([0, 1, 1, 0], [0, 1, 0, 1])) print(xor_lists([True, True, True, False], [False, True, False, True]))
Please note that the resulting list will contain the same type of elements as the input lists (either integers or booleans). If the lists are not of the same length, the function will raise a ValueError exception
Python xor between two strings
You can also use the xor( ^) operator to perform a bitwise XOR operation on two strings. However, this operation will only work if both strings are of the same length, and the strings must contain only ASCII characters.
Below is an example of how you could implement a function to perform a bitwise XOR operation on two strings:
def xor_strings(s1, s2): b1 = s1.encode() b2 = s2.encode() # XOR the bytes result = b'' for x1, x2 in zip(b1, b2): result += bytes([x1 ^ x2]) # Return the XOR'd string return result.decode() print(xor_strings('hello', 'world'))
The final string may contain non-printable characters, as the XOR operation is performed on the individual bytes of the strings, and not on the characters themselves. Below is the output of the above code snipped.
Python xor between two hexadecimal values
We can also use the xor( ^) operator to perform a bitwise XOR operation on two hexadecimal values. Please refer to the below code snippet.
def xor_hex(h1, h2): # Convert the hexadecimal values to integers i1 = int(h1, 16) i2 = int(h2, 16) # XOR the integers result = i1 ^ i2 # Return the result as a hexadecimal string return hex(result) print(xor_hex('0x1', '0x2')) print(xor_hex('0x7', '0x4'))
The above function takes two hexadecimal values as input and returns the bitwise XOR of the two values as a hexadecimal string.
The hexadecimal values must first be converted to integers using the int() function and a base of 16. The ^ operator can then be used to perform the bitwise XOR operation on the integers. The result of the operation can be converted back to a hexadecimal string using the hex() function.
The bitwise XOR of 0x1 (1 in decimal) and 0x2 (2 in decimal) is 0x3 (3 in decimal), because only the first bit is different. Similarly, the bitwise XOR of 0x 7 (7 in decimal) and 0x 4 (4 in decimal) is 0x 3 (6 in decimal).
XOR in Python using Operator Module
In Python, you can use the operator module to perform a bitwise XOR operation on two values. To use the operator module, you will first need to import it. Below is an example of how you could use the operator module to perform a bitwise XOR operation in Python:
import operator def xor(a, b): return operator.xor(a, b) print(xor(1, 2)) print(xor(7, 4))
The xor function from the operator module works with any values that support the bitwise XOR operation, including integers, booleans, and strings. Below is the output for the same.
Conclusion
I hope you have liked this tutorial on the python xor function. In this tutorial, we have learned the python xor function with multiple examples. Please do let me know if you are facing any issues while following along.