Table of contents
1.
Introduction
2.
Bitwise AND Operator
2.1.
Python
3.
Bitwise OR Operator
3.1.
Python
4.
Bitwise XOR Operator
4.1.
Python
5.
Bitwise NOT Operator
5.1.
Python
6.
Bitwise Shift Operations
6.1.
Python Bitwise Left Shift
6.2.
Python
6.3.
Python Bitwise Right Shift
6.4.
Python
7.
Bitwise Operator Overloading
7.1.
Python
8.
Frequently Asked Questions
8.1.
Why use bitwise operators in Python?
8.2.
Can bitwise operators be used with any data type?
8.3.
Are bitwise shifts equivalent to multiplying and dividing by two?
9.
Conclusion
Last Updated: Jun 2, 2024
Easy

Python Bitwise Operators

Author Riya Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Bitwise operators in Python is an important concept for direct binary manipulation of integers. These operations are critical in areas like embedded systems programming, cryptography, and digital signal processing, where control over individual bits is necessary for optimizing performance and efficiency.

Python Bitwise Operators

In this article we will talk about the common bitwise operators: AND, OR, XOR, NOT, along with bit shifting mechanisms.Each operator offers specific functionalities for altering binary data, facilitating operations such as bit masking, quick arithmetic, and data encoding. 

Bitwise AND Operator

The Bitwise AND operator in Python is a simple but very cruical tool used for handling binary data. The operator takes two numbers, converts them into binary format, & then performs the AND operation on each pair of corresponding bits. The operation itself is easy and straightforward: it returns 1 if both bits are 1, & 0 otherwise. This behavior makes it invaluable for tasks like clearing specific bits in a bitmask or checking if a particular bit is set.

For example, consider a scenario where you need to determine whether certain flags in a configuration setting are enabled. Each flag is represented by a bit position in an integer, & by using the AND operation with a mask, you can isolate specific flags.

Code Example :

  • Python

Python

# Define two integers
a = 29 # binary: 11101
b = 45 # binary: 101101

# Perform bitwise AND
result = a & b

# Print the result
print(f"The result of {a} & {b} is {result} (binary: {bin(result)})")
You can also try this code with Online Python Compiler
Run Code

Output

The result of 29 & 45 is 13 (binary: 0b1101)


In this code, the bitwise AND operation between 29 & 45 results in 13, which in binary is 1101. This result is achieved by comparing each bit of 29 & 45 from right to left:

1 AND 1 gives 1
0 AND 0 gives 0
1 AND 1 gives 1
1 AND 0 gives 0
1 AND 1 gives 1 (ignoring the leftmost bits as they don't align)

Bitwise OR Operator

The Bitwise OR operator is another fundamental tool in Python's set of bitwise manipulations. Similar to the AND operator, it works directly on the binary representations of integers. Where it differs, however, is in its operational rule: the Bitwise OR operator returns a 1 for each bit comparison where at least one of the bits is 1. This makes it particularly useful for setting specific bits in a number, say, to turn on certain features represented by bits within a system's settings.

For example, if you are managing user permissions where each bit in a number represents a different permission level, you can use the OR operation to activate various permissions simultaneously.

Code Example : 

  • Python

Python

# Define two integers
a = 12 # binary: 1100
b = 25 # binary: 11001

# Perform bitwise OR
result = a | b

# Print the result
print(f"The result of {a} | {b} is {result} (binary: {bin(result)})")
You can also try this code with Online Python Compiler
Run Code

Output

The result of 12 | 25 is 29 (binary: 0b11101)


In this example, performing the bitwise OR operation on 12 and 25 gives 29, which is 11101 in binary:

0 OR 1 gives 1
0 OR 0 gives 0
1 OR 1 gives 1
1 OR 0 gives 1
1 OR 1 gives 1 (leftmost bit, considering the longer length of b)


Note : The Bitwise OR operator's ability to combine bits from two numbers makes it indispensable for constructing values that are made up of multiple smaller, binary-coded parts.

Bitwise XOR Operator

The Bitwise XOR (exclusive OR) operator is a crucial tool for programmers dealing with low-level data manipulation. This operator compares two bits and returns 1 if the bits are different, and 0 if they are the same. This unique property is widely used in algorithms for error detection and correction, as well as for various encryption techniques. By toggling bits, the XOR operator can invert selected bits in a number without affecting the others, making it perfect for tasks where you need to flip specific bits while leaving the rest unchanged.

For example, consider a scenario where you need to encrypt a simple data transmission. By XORing the data with a key, you change the original bits, effectively encrypting the data. To decrypt it, you simply XOR the encrypted data with the same key.

Code Example : 

  • Python

Python

# Define two integers
a = 34 # binary: 100010
b = 52 # binary: 110100

# Perform bitwise XOR
result = a ^ b

# Print the result
print(f"The result of {a} ^ {b} is {result} (binary: {bin(result)})")
You can also try this code with Online Python Compiler
Run Code

Output

The result of 34 ^ 52 is 22 (binary: 0b10110)


In this code, XORing 34 and 52 results in 18, which is 10010 in binary:

1 XOR 1 gives 0
0 XOR 0 gives 0
0 XOR 1 gives 1
0 XOR 0 gives 0
1 XOR 1 gives 0


This example illustrates how the XOR operator can be used to both encode and decode data simply by applying the same operation twice with the same key.

Bitwise NOT Operator

The Bitwise NOT operator, often denoted as ~, is straightforward in its function but profound in its utility. This operator works by inverting each bit of a number—turning each 1 into a 0 and each 0 into a 1. It's particularly useful in scenarios where you need to quickly flip all bits of an operand, which can be helpful in generating complement forms of binary numbers, a common task in systems programming and digital circuit design.

In Python, the Bitwise NOT operation might initially confuse due to Python's handling of integer representation. Python uses a signed number system, which means the results of a bitwise NOT may appear negative if you're not familiar with two's complement notation, which is a method of representing signed numbers in binary.

Let’s see how we can use it : 

  • Python

Python

# Define an integer
a = 25 # binary: 11001

# Perform bitwise NOT
result = ~a

# Print the result
print(f"The result of ~{a} is {result} (binary: {bin(result)})")
You can also try this code with Online Python Compiler
Run Code

Output

The result of ~25 is -26 (binary: -0b11010)


In this example, applying the NOT operator to the binary of 25 (which is 11001) flips all bits. Since Python represents negative numbers using two's complement, the result appears as -26. Here's a  breakdown:

  • Original binary of 25: 000...11001 (preceding zeros are normally omitted)
     
  • After flipping the bits: 111...00110
     
  • Two's complement (for representing -26): Invert all bits and add 1, resulting in the binary for -26

Bitwise Shift Operations

Bitwise shift operations in Python slide the bit pattern to the left or right. These operations are classified into two types: the left shift (<<) and the right shift (>>). Both types are integral to performance-critical applications such as graphics rendering and mathematical computations, where operations need to be as efficient as possible.

Python Bitwise Left Shift

The left shift operation (<<) shifts the bits of a number to the left by a specified number of positions. This is akin to multiplying the number by 2n , where n is the number of positions shifted. For instance, shifting a number one bit to the left doubles it, just as multiplying by 2 would.

Here’s an example:

  • Python

Python

# Define an integer
a = 5 # binary: 101

# Perform bitwise left shift by 2 positions
result = a << 2

# Print the result
print(f"The result of {a} << 2 is {result} (binary: {bin(result)})")
You can also try this code with Online Python Compiler
Run Code

Output

The result of 5 << 2 is 20 (binary: 0b10100)


In this code, shifting 5 (which is 101 in binary) left by 2 positions results in 20, which is 10100 in binary. This shift effectively multiplies 5 by 22  (or 4), demonstrating how the left shift can be used for quick multiplication by powers of two.

Python Bitwise Right Shift

Conversely, the right shift operation (>>) shifts the bits of a number to the right by a specified number of positions, which is equivalent to integer division by 2n . This operation is useful for efficiently dividing numbers while discarding the remainder.

Let’s ee how to use this : 

  • Python

Python

# Define an integer
a = 20 # binary: 10100

# Perform bitwise right shift by 2 positions
result = a >> 2

# Print the result
print(f"The result of {a} >> 2 is {result} (binary: {bin(result)})")
You can also try this code with Online Python Compiler
Run Code

Output

The result of 20 >> 2 is 5 (binary: 0b101)


In this example, shifting 20 (which is 10100 in binary) right by 2 positions results in 5, which is 101 in binary. This shift effectively divides 20 by 22(or 4), illustrating how the right shift can be used for quick division by powers of two.

Note : Bitwise shift operations provide a method for handling data at a very basic level, which offers  a combination of simplicity and efficiency that is particularly very useful in low-level programming and performance-sensitive applications.

Bitwise Operator Overloading

In Python, operator overloading allows the same operator to have different meanings based on the context. This feature is particularly useful when working with custom objects that require specific implementations of standard operators. Bitwise operators, like any other operator, can be overloaded to perform operations beyond their typical use with integers.

For example, you might have a class that represents a data packet for network transmission. You could overload the bitwise AND, OR, and XOR operators to handle merging or comparing packet data efficiently.

Here's an example of how you could implement this in Python by defining a simple class that overloads the bitwise AND operator:

  • Python

Python

class DataPacket:
def __init__(self, data):
self.data = data

def __and__(self, other):
if isinstance(other, DataPacket):
# Combine data using bitwise AND
return DataPacket(self.data & other.data)
return NotImplemented

def __repr__(self):
return f"DataPacket({bin(self.data)})"

# Create two data packets
packet1 = DataPacket(0b1101)
packet2 = DataPacket(0b1011)

# Use the overloaded bitwise AND operator
combined_packet = packet1 & packet2

# Print the result
print(f"Combined Data Packet: {combined_packet}")
You can also try this code with Online Python Compiler
Run Code

Output

Combined Data Packet: DataPacket(0b1001)


In this code, two instances of DataPacket are created with binary data. When the & operator is used between these instances, the __and__ method is called, which performs a bitwise AND operation on the data attributes of the packets. The result is a new DataPacket instance containing the combined data.

Note : This example shows how operator overloading can be used to extend the functionality of Python’s built-in operators to work with user-defined objects, enhancing readability and simplicity of the code.

Frequently Asked Questions

Why use bitwise operators in Python?

Bitwise operators provide a method to manipulate individual bits of data, which is faster and more memory-efficient than working with higher-level abstractions. This makes them invaluable in performance-critical applications such as image processing and cryptography.

Can bitwise operators be used with any data type?

No, bitwise operators primarily work with integers in Python. When you use them with non-integer types, Python will raise a TypeError. To use these operators with custom data types, such as objects, you need to explicitly overload them in your class definition.

Are bitwise shifts equivalent to multiplying and dividing by two?

Yes, generally speaking, left-shifting a number by one is equivalent to multiplying it by two, and right-shifting a number by one is equivalent to dividing it by two, discarding any remainder. However, the actual effect can depend on the number and the number of shifts.

Conclusion

In this article, we have learned about Python’s bitwise operators & their significance in programming. We discussed the bitwise AND, OR, XOR, NOT operators, and both left & right shifts, understanding how each can be used to manipulate data efficiently at the bit level. In addition to this, we also looked at operator overloading to extend the functionality of these operators for custom objects. These tools are powerful for anyone looking to perform low-level data manipulation directly, offering both performance benefits & direct control over data handling.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass