×

Exclusive OR in Python

In Python, the exclusive OR (XOR) operator is represented by the caret symbol (^). It compares each bit of the first operand to the corresponding bit of the second operand, and if they are different, the corresponding result bit is set to 1. If they are the same, the corresponding result bit is set to 0.

Here is an example of using the XOR operator in Python:

Example:

a = 5  # binary: 101
b = 3  # binary: 011
c = a ^ b  # binary: 110
print(c)  

Output:

 6

In this example, the binary representation of a is 101, and the binary representation of b is 011. When we perform the XOR operation, we compare each bit of a to the corresponding bit of b:

  • The first bit of a (the leftmost) is 1 and the first bit of b is 0, so the first bit of the result is 1.
  • The second bit of a is 0 and the second bit of b is 1, so the second bit of the result is 1.
  • The third bit of a is 1 and the third bit of b is 1, so the third bit of the result is 0.

So, the binary representation of the result is 110, which is equivalent to the decimal value 6. In python you can use the operator ^ for XOR operation.

The XOR operator in Python is a bitwise operator that compares each bit of the first operand to the corresponding bit of the second operand. If the bits are different, the corresponding result bit is set to 1. If they are the same, the corresponding result bit is set to 0.

The XOR operator can be used to perform various bit manipulation tasks such as flipping specific bits, setting or clearing bits, and more. For example, you can use the XOR operator to toggle specific bits in an integer without affecting the other bits.

Here is an example of using the XOR operator to toggle the third bit of a number:

x = 5  # binary: 101
mask = 1 << 2  # binary: 100
x = x ^ mask  # binary: 001
print(x)  

Output:

1

In this example, we first create a mask with the value 1 << 2, which is equivalent to shifting the binary number 1 to the left by 2 positions, resulting in binary 100. Then, we use the XOR operator to toggle the third bit of x by XORing it with the mask. This provides result in a new value of 1, which is the decimal representation of the binary number 001.

The XOR operator can be used on integer types in Python (int, long) as well as bytes and byte array. We can also use the XOR() function from the operator module to perform the same operation.

from operator import xor
print(xor(5, 3)) #6

Use of XOR in Python

The XOR operator in Python can be used in a variety of ways, some examples are as follows:

  • Bit manipulation: As mentioned before, the XOR operator can be used to perform various bit manipulation tasks such as flipping specific bits, setting or clearing bits, and more.
  • Encryption and decryption: The XOR operator can be used in simple encryption and decryption algorithms, such as the XOR Cipher. It can be used to encrypt plaintext by XORing it with a secret key, and then decrypting it by XORing it again with the same key.
  • Error detection and correction: The XOR operator can be used in error detection and correction codes such as the Hamming code, which uses XOR to detect and correct errors in data transmission.
  • Data compression: The XOR operator can be used in data compression algorithms, such as the LZ78 algorithm to compress data by identifying and encoding repeated patterns.
  • Boolean logic: The XOR operator can be used as a logical operator to implement the XOR function in Boolean logic. It returns true if one and only one of its operands is true.
  • Set membership test: XOR operator can be used to check if a number is present in a set or not. The number is XORed with all the numbers in the set and the result is checked if it is present in the set or not.

Related Topics

Python sum() function

Python sum() function The sum() function in python sums start and the items of an iterable from left to right and returns the total.  Syntax sum(iterable[, start]) Parameter iterable: This parameter represents the sequence to sum. start: It is optional...

1 minute read.

Python globals() function

Python globals() function The globals() function in Python returns the value of the named attribute of object where the ‘name’ must be a string. Syntax globals() Parameter NA Return This function returns the global symbol table as a dictionary. Example...

1 minute read.

How to Install Scikit-Learn

Sklearn or Scikit-learn is a python library used for machine learning. It contains many features like classification, regression, clustering, and Dimensionality reduction algorithms. Sklearn is used to build machine learning...

3 minutes read.

Python Kwargs Example

In this article, we'll talk about Python's kwargs notion. In Python, kwargs has two stars and passes a variable number of keyworded argument lists to the function, whereas args has...

5 minutes read.

Difference between Package and Module in Python

What are Python modules? A file with the “.py” suffix that includes Python or C executable code is known as a module. Multiple Python commands and expressions make compose a module....

3 minutes read.

Add Dictionary to Dictionary in Python

Dictionary in python: Python's execution of a data model, known more commonly as an implicit array, is a dictionary. A dictionary is made up of a group of key-value pairs. Each...

4 minutes read.

Importing Numpy in Pycharm

Numpy : Numpy is one of the important library in python. The abbreviation of numpy is “Numerical python” or “Numeric Python”. This library is mainly used to access arrays. Numpy was created...

5 minutes read.

Python Matrix Operations

Python Matrix In this section of the Python tutorial, we will look at the introduction of the matrix in Python programming. We will perform many operations on the Python matrix using...

21 minutes read.

Nested Tuple in Python

If you are a Python learner, this page contains all the information that helps you know about nested tuple and how to access it in python. What is a Tuple? Multiple items...

4 minutes read.

Python Percentage Sign

In Python, the percentage sign significantly completes two things. They are: It goes about as a Modulo administrator. It helps in string organizing. Allow us to see every one of them plainly. Modulo operator: Like...

2 minutes read.

XXhash Python Examples

XXhash Python: xxHash is an extremely rapid hash calculation that operates inside the confines of RAM. Code is incredibly convenient, and hashes (almost nothing/large endian) are same at all levels. Execution of...

4 minutes read.

Difference between Python and CPP

Difference between Python and C++ We all know that both C++ and Python are two of the most popular programming languages. Both C++ and Python shares some basic similarities such as...

6 minutes read.

Python Deep Copy and Shallow Copy

Assignment statements in Python create bindings between a target and an object, not copies of them. The = operator only makes a new variable that shares the reference to the...

3 minutes read.

Performing Transaction Using Python MySQL

Transaction A Transaction contains a set of SQL commands used to change the data in the dataset. If we say transaction, it means that the data in the database has changed....

3 minutes read.

Python zip() Function

Python zip() Function The zip() function makes an iterator that aggregates elements from each of the iterables and returns an iterator of tuples. Syntax zip(*iterables) Parameter iterables: Iterator objects that will be joined together Return This function...

1 minute read.

Python Infinity

Introduction We will discover how to define an infinite number in Python in this tutorial. Infinity, as we all know, is a value that cannot be defined and can either be...

5 minutes read.

Introduction to Scratch programming

Scratch programming is generally designed for children who may create digital stories, games, and animations using the computer language Scratch, which has the largest kid-focused community in the world. Scratch...

3 minutes read.

How to read data from com port in python

Comport, the I/O interface is known as a COM port that allows the connection for a serial device to a computer. COM ports are sometimes referred to as serial ports....

3 minutes read.

Writing to Excel using Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.

Python id() function

Python id() function The id() function in Python returns an id for the specified object where all the objects in has its own unique id. Syntax id(object) Parameter object: This parameter represents any object, String, Number, List,...

1 minute read.