1. Home

Python Tutorials - Elevate Your Coding Skills with Comprehensive Tutorials

Discover Python tutorials covering everything from the basics to advanced topics. Whether you're new to programming or looking to level up your skills, our tutorials will guide you every step of the way

• 201 Lessons
• 33 Hours
34.Â

# Bitwise operators in Python

Updated on 14/09/20247,167 Views

## Introduction

Bitwise operators in Python are fundamental tools for performing bit-level operations on integers. These operators manipulate individual bits, allowing for efficient and precise control over binary data. In this extensive guide, we'll delve into the details of bitwise operator in Python, exploring their purpose, functionality, and practical applications.

## Overview

Bitwise operators are essential in low-level programming, embedded systems, and tasks that require fine-grained bit manipulation. Python provides several bitwise operators, each serving a unique purpose. These operators include AND, OR, NOT, XOR, and shift operators. Let's explore each of these in detail.

## Bitwise Operators

Bitwise operators in Python are fundamental operations that work at the binary level, enabling precise control over binary data. They perform operations on individual bits of integers by converting the integers to binary format, performing bit-level operations, and then converting the result back to decimal form. These operators are used for tasks such as bit manipulation, flag settings, and low-level data processing.

 Operator Description Example Result (Decimal) Bitwise AND (&) Returns 1 if both bits are 1, else 0 5 & 3 1 Bitwise OR (` `) Returns 1 if at least one bit is 1, else 0 `5 Bitwise NOT (~) Inverts all bits ~5 -6 Bitwise XOR (^) Returns 1 if bits are different else, 0 5 ^ 3 6

### Bitwise AND Operator (&)

The bitwise AND operator (&) is used to perform a binary AND operation on corresponding bits of two integers. It returns a new integer with bits set to 1 only if both operands have corresponding bits set to 1.

Example:

`Codea = 5 Â # 101 in binaryb = 3 Â # 011 in binaryresult = a & b Â # 001 in binary, which is 1 in decimal`

### Bitwise OR Operator (|)

The bitwise OR operator (|) is used to perform a binary OR operation on corresponding bits of two integers. It returns a new integer with bits set to 1 if at least one of the corresponding bits in the operands is 1.

Example:

`Codea = 5 Â # 101 in binaryb = 3 Â # 011 in binaryresult = a | b Â # 111 in binary, which is 7 in decimal`

### Bitwise NOT operator in Python (~)

The bitwise NOT operator in Python (~) inverts all the bits of a single integer. It returns a new integer with all bits reversed (0s become 1s, and 1s become 0s).

Example:

`Codea = 5 Â # 101 in binaryresult = ~a Â # -6 in decimal`

### Bitwise XOR Operator in Python (^)

The bitwise XOR operator in Python (^) is used to perform a binary XOR operation on corresponding bits of two integers. It returns a new integer with bits set to 1 if exactly one of the corresponding bits in the operands is 1.

Example:

`Codea = 5 Â # 101 in binaryb = 3 Â # 011 in binaryresult = a ^ b Â # 110 in binary, which is 6 in decimal`

Here is Python code that demonstrates the bitwise logical operators in Python (&, |, ~, ^) in action:

`Code# Bitwise AND operator (&)a = 12 Â # Binary: 1100b = 6 Â  # Binary: 0110result_and = a & b Â # Binary result: 0100 (Decimal: 4)# Bitwise OR operator (|)x = 10 Â # Binary: 1010y = 3 Â  # Binary: 0011result_or = x | y Â # Binary result: 1011 (Decimal: 11)#Â Bitwise NOT operator in PythonÂ (~)m = 7 Â  # Binary: 0111result_not = ~m Â # Binary result: 1000 (Decimal: -8)#Â Bitwise XOR operator in Python(^)p = 15 Â # Binary: 1111q = 6 Â  # Binary: 0110result_xor = p ^ q Â # Binary result: 1001 (Decimal: 9)# Printing the resultsprint("Bitwise AND result:", result_and)print("Bitwise OR result:", result_or)print("Bitwise NOT result:", result_not)print("Bitwise XOR result:", result_xor)`

In this code:

• result_and stores the result of the bitwise AND operation between a and b.
• result_or stores the result of the bitwise OR operation between x and y.
• result_not stores the result of the bitwise NOT operation on m.
• result_xor stores the result of the bitwise XOR operation between p and q.

Output:

`Bitwise AND result: 4Bitwise OR result: 11Bitwise NOT result: -8Bitwise XOR result: 9`

## Bitwise Shift Operators

Bitwise Shift Operators are operators in Python used to shift the bits of an integer left or right by a specified number of positions. These bitwise left and right shift operators in Python manipulate the binary representation of an integer, multiplying or dividing it by powers of 2.

 Bitwise left and right shift operator in Python Description Example Result (Decimal) Bitwise Left Shift (<<) Shifts bits left by specified count 5 << 2 20 Bitwise Right Shift (>>) Shifts bits right by specified count 16 >> 2 4

### Bitwise Right Shift Operator in Python (>>)

The bitwise right shift operator in Python (>>) shifts the bits of an integer to the right by a specified number of positions. This operation effectively divides the integer by 2, raised to the power of the specified number.

Example:

`Codea = 8 Â # 1000 in binaryresult = a >> 2 Â # Shift right by 2 positions: 0010 in binary, which is 2 in decimal`

### Bitwise Left Shift Operator in Python (<<)

The bitwise left shift operator in Python (<<) shifts the bits of an integer to the left by a specified number of positions. This operation effectively multiplies the integer by 2 raised to the power of the specified number.

Example:

`Codea = 2 Â # 0010 in binaryresult = a << 3 Â # Shift left by 3 positions: 1000 in binary, which is 8 in decimal`

Here's Python code that demonstrates the bitwise shift operators (<< and >>) in action:

`Code# BitwiseÂ Left Shift operator in PythonÂ (<<)num_left = 5 Â  # Binary: 0000 0101shift_count = 2result_left_shift = num_left << shift_count Â # Shift left by 2 positions: 0001 0100 (Decimal: 20)#Â Bitwise Right Shift operator in PythonÂ (>>)num_right = 16 Â # Binary: 0001 0000shift_count = 2result_right_shift = num_right >> shift_count Â # Shift right by 2 positions: 0000 0100 (Decimal: 4)# Printing the resultsprint("Bitwise Left Shift result:", result_left_shift)print("Bitwise Right Shift result:", result_right_shift)`

In this code:

• result_left_shift stores the result of the bitwise left shift operation on num_left. We shift the bits left by 2 positions.
• result_right_shift stores the result of the bitwise right shift operation on num_right. We shift the bits right by 2 positions.

Output:

`Bitwise Left Shift result: 20Bitwise Right Shift result: 4`

Python allows you to overload some bitwise operators (&, |, ~, ^) for custom classes by defining special methods such as __and__(), __or__(), __invert__(), and __xor__().

`Codeclass ComplexNumber:Â  Â  def __init__(self, real, imaginary):Â  Â  Â  Â  self.real = realÂ  Â  Â  Â  self.imaginary = imaginaryÂ  Â  def __str__(self):Â  Â  Â  Â  return f"{self.real} {self.imaginary}i"Â  Â  def __add__(self, other):Â  Â  Â  Â  if isinstance(other, ComplexNumber):Â  Â  Â  Â  Â  Â  real_sum = self.real other.realÂ  Â  Â  Â  Â  Â  imag_sum = self.imaginary other.imaginaryÂ  Â  Â  Â  Â  Â  return ComplexNumber(real_sum, imag_sum)Â  Â  Â  Â  else:Â  Â  Â  Â  Â  Â  raise ValueError("Addition is only supported for ComplexNumber objects.")# Usagenum1 = ComplexNumber(2, 3)num2 = ComplexNumber(1, 4)result = num1+num2print(result) Â # Output: 3+7i`

`Codeclass Point:Â  Â  def __init__(self, x, y):Â  Â  Â  Â  self.x = xÂ  Â  Â  Â  self.y = yÂ  Â  def __str__(self):Â  Â  Â  Â  return f"Point({self.x}, {self.y})"Â  Â  def __sub__(self, other):Â  Â  Â  Â  if isinstance(other, Point):Â  Â  Â  Â  Â  Â  x_diff = self.x - other.xÂ  Â  Â  Â  Â  Â  y_diff = self.y - other.yÂ  Â  Â  Â  Â  Â  return Point(x_diff, y_diff)Â  Â  Â  Â  else:Â  Â  Â  Â  Â  Â  raise ValueError("Subtraction is only supported for Point objects.")# Usagepoint1 = Point(5, 3)point2 = Point(2, 2)result = point1 - point2print(result) Â # Output: Point(3, 1)`

`Codeclass Matrix:Â  Â  def __init__(self, data):Â  Â  Â  Â  self.data = dataÂ  Â  def __str__(self):Â  Â  Â  Â  return "\n".join([" ".join(map(str, row)) for row in self.data])Â  Â  def __mul__(self, other):Â  Â  Â  Â  if isinstance(other, Matrix):Â  Â  Â  Â  Â  Â  result = [[0 for _ in range(len(other.data[0]))] for _ in range(len(self.data))]Â  Â  Â  Â  Â  Â  for i in range(len(self.data)):Â  Â  Â  Â  Â  Â  Â  Â  for j in range(len(other.data[0])):Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  for k in range(len(other.data)):Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  Â  result[i][j] = self.data[i][k] * other.data[k][j]Â  Â  Â  Â  Â  Â  return Matrix(result)Â  Â  Â  Â  else:Â  Â  Â  Â  Â  Â  raise ValueError("Multiplication is only supported for Matrix objects.")# Usagematrix1 = Matrix([[1, 2], [3, 4]])matrix2 = Matrix([[5, 6], [7, 8]])result = matrix1 * matrix2print(result)# Output:# 19 22# 43 50`

`Codeclass Fraction:Â  Â  def __init__(self, numerator, denominator):Â  Â  Â  Â  self.numerator = numeratorÂ  Â  Â  Â  self.denominator = denominatorÂ  Â  def __str__(self):Â  Â  Â  Â  return f"{self.numerator}/{self.denominator}"Â  Â  def __truediv__(self, other):Â  Â  Â  Â  if isinstance(other, Fraction):Â  Â  Â  Â  Â  Â  result_numerator = self.numerator * other.denominatorÂ  Â  Â  Â  Â  Â  result_denominator = self.denominator * other.numeratorÂ  Â  Â  Â  Â  Â  return Fraction(result_numerator, result_denominator)Â  Â  Â  Â  else:Â  Â  Â  Â  Â  Â  raise ValueError("Division is only supported for Fraction objects.")# Usagefraction1 = Fraction(1, 2)fraction2 = Fraction(3, 4)result = fraction1 / fraction2print(result) Â # Output: 2/3`

## Practical Applications

Now that we understand the bitwise operators and their functionality, let's explore some practical applications of these operators in Python.

1. Binary Data Manipulation:

Bitwise operators are invaluable when dealing with binary data, such as file I/O, image processing, or cryptography. For example, you can use bitwise AND to apply masks to specific bits in a binary stream or perform bitwise XOR operations for encryption.

2. Embedded Systems and Microcontrollers:

In embedded systems programming, where resource efficiency is crucial, bitwise operations are extensively used. Controlling hardware peripherals, setting configuration registers, and handling communication protocols often require precise bit manipulation.

In networking, IP address manipulation often involves bitwise operations. For instance, subnet masking and CIDR notation rely on bitwise AND to determine network and host portions of an IP address.

4. Graphics and Image Processing:

Bitwise operators are fundamental in graphics and image processing applications. They are used to manipulate pixel values, apply filters, and create various visual effects.

5. Game Development:

Game developers use bitwise operations for tasks such as collision detection, game state management, and rendering optimizations. These operations help enhance the performance and visual appeal of video games.

6. Ethical and Societal Implications:

While bitwise operators themselves are tools, the applications built on top of them can have profound ethical and societal implications. Here are some key considerations.

## Conclusion

Bitwise operators in Python are powerful tools for working with binary data and performing bit-level operations on integers. It is essential for developers to understand their functionality and practical applications, especially those working in low-level programming, embedded systems, or data manipulation tasks.

## FAQs

1. What are bitwise operators?

Bitwise operators in Python are used to perform bit-level operations on integers. They include AND (&), OR (|), NOT (~), XOR (^), and shift operators (>> and <<).

2. Where are bitwise operators commonly used?

Bitwise operators are commonly used in low-level programming, embedded systems, binary data manipulation, networking, image processing, game development, and more.

3. How do I use bitwise operators in Python?

You can use bitwise operators by applying them to integers in binary representation. For example, to perform a bitwise AND operation between a and b, use the expression result = a & b.

Director of Engineering

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working â€¦Read More

###### Need More Help? Talk to an Expert
+91
*
By clicking, I accept theT&Cand
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.

Talk to our experts. Weâ€™re available 24/7.

Indian Nationals

1800 210 2020

Foreign Nationals

+918045604032

## Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...