# 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.

Contents

## 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

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)
```

Output

`9`

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))

```

Output

```30
False
False
True
True```

## 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 & (1 << i)
b2 = y & (1 << i)
b1 = min(b1, 1)
b2 = min(b2, 1)

# Checks if both integers are either 1s or 0s
# if not proceeds to peform standard OR operation
xorBit = 0
if (b1 & b2):
xorBit = 0
else:
xorBit = (b1 | b2)

# Update the resultant variable
res <<= 1;
res |= xorBit
return res

# Integers to be passed into the function
x = int(input("enter an integer: "))
y = int(input("enter an integer: "))
print("XOR of X and Y is", XORFunction(x, y))
```

Output

```enter an integer: 10
enter an integer: 3
XOR of X and Y is 9
```

## 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);

```

Output

## 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))
```

Output

`0x5ee5`

## 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))
```

Output

`39`

## 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.

How do you get the logical XOR of two variables in Python?

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.

Subscribe
Notify of