Understanding Bitwise Operators in Python with Code Examples

Updated on July 29, 2024

Article Outline

Ever wondered how to manipulate the bits around in your code directly? Or, maybe you’re interested in how low-level operations work in Python. These are questions that pop up quite often when covering programming a bit more advanced.

 

Bitwise operators in Python provide operations at the bit level and are very powerful tools for special tasks where one needs efficient and exact control over binary data. We will delve deeper into the land of bitwise operators, showing how they could make our code more effective and efficient.

Detailed Explanation and Code Examples of Each Bitwise Operator

1. The Bitwise AND Operator (&)

The bitwise AND operator compares each bit of two integers and returns a new integer with bits set to 1 only when both corresponding bits are 1. This is often used in masking operations, especially wherever isolating specific bits is required within an integer.

Code Example

a = int(input("Enter the first integer: ")) b = int(input("Enter the second integer: ")) result = a & b print("Bitwise AND result:", result)

Output:

output

2. The Bitwise OR Operator (|)

The bitwise OR operator makes a bit-by-bit comparison between two integers and returns a new integer with bits set to 1 where at least one of the corresponding bits in comparison is 1. This is useful when we want to turn certain bits within an integer into 1 without affecting the other bits.

Code Example

a = int(input("Enter the first integer: ")) b = int(input("Enter the second integer: ")) result = a | b print("Bitwise OR result:", result)

Output:

output

3. The Bitwise NOT Operator (~)

The bitwise NOT operator inverts all the bits in an integer: 1 changes to 0, and 0 changes to 1. This operator may be helpful in such operations that require flipping all the bits in a binary representation.

Code Example

a = int(input("Enter an integer: ")) result = ~a print("Bitwise NOT result:", result)

Output:

output

4. The Bitwise XOR Operator (^)

The bitwise XOR operator compares each of the corresponding bits of two integers and returns a new integer that has most of those bits set to 1 only when one of the corresponding bits is 1. This operator can be readily used to toggle certain bits within an integer.

Code Example

a = int(input("Enter the first integer: ")) b = int(input("Enter the second integer: ")) result = a ^ b print("Bitwise XOR result:", result)

Output:

output

5. The Left Shift Operator (<<)

The left shift operator shifts the bits of an integer to the left by the specified number of positions, filling its rightmost bits with zeros. This operator is equivalent to multiplying the integer by 2, raised to the power of the number of positions shifted.

Code Example

a = int(input("Enter an integer: ")) shift = int(input("Enter the number of positions to shift left: ")) result = a << shift print("Left Shift result:", result)

Output:

output

6. The Right Shift Operator (>>)

The right shift operator shifts the bits of an integer to the right by a specified number of positions, ordinarily discarding the rightmost; this is equivalent to integer division by 2 raised to the power of the positions shifted.

Code Example

a = int(input("Enter an integer: ")) shift = int(input("Enter the number of positions to shift right: ")) result = a >> shift print("Right Shift result:", result)

Output:

output

*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Exploring Bitwise Operator Overloading in Python

Ever wondered if you could customise how bitwise operators in Python work with your objects? The good news is that we can do that in Python.

 

By using operator overloading, we can define how our custom classes behave with bitwise operators like &, |, ~, and ^.

How Does Operator Overloading Work?

Python allows us to redefine the behaviour of operators for user-defined classes.

 

We do this by defining special methods in our class.

 

For bitwise operators, the methods are:

  • __and__ for &
  • __or__ for |
  • __xor__ for ^
  • __invert__ for ~
  • __lshift__ for <<
  • __rshift__ for >>

Example: Custom Class with Bitwise Operator Overloading

Let’s create a class that represents a simple binary number and overloads the bitwise operators in Python.

class BinaryNumber:

def __init__(self, value): self.value = value  def __and__(self, other): return BinaryNumber(self.value & other.value)  def __or__(self, other): return BinaryNumber(self.value | other.value)  def __xor__(self, other): return BinaryNumber(self.value ^ other.value)  def __invert__(self): return BinaryNumber(~self.value)  def __lshift__(self, other): return BinaryNumber(self.value << other)  def __rshift__(self, other): return BinaryNumber(self.value >> other)  def __str__(self): return bin(self.value)  # Example usage a = BinaryNumber(12) b = BinaryNumber(5)  print("AND operation:", a & b) print("OR operation:", a | b) print("XOR operation:", a ^ b) print("NOT operation:", ~a) print("Left shift operation:", a << 2) print("Right shift operation:", a >> 2)

Real-World Applications and Use Cases for Bitwise Operators

You might wonder, where do we actually use bitwise operators in real life? Bitwise operators in Python are incredibly useful in several areas.

Binary Data Manipulation

When dealing with file I/O, image processing, or cryptography, bitwise operations can help manipulate binary data efficiently.

Embedded Systems and Microcontrollers

In embedded systems, resources are limited. Bitwise operations allow for precise control over hardware peripherals and configuration registers.

Networking and IP Addressing

Network applications often involve IP address manipulation. Bitwise operators are essential for subnet masking and CIDR notation.

Graphics and Image Processing

In graphics, bitwise operations are used to manipulate pixel values, apply filters, and create visual effects.

Game Development

Game developers use bitwise operations for tasks like collision detection and game state management. These operations help optimise performance and enhance the visual appeal of games.

Conclusion

Bitwise operators in Python are strong features that let one work directly with binary data. Using such operators, we can further optimise our code to be more efficient by performing complex operations with much better speed.

 

Be it data manipulation, embedded systems, networking, graphics, or game development; bitwise operators become essential when one needs to exert fine-grained control or facilitate performance optimisation. Let’s continue exploring and leveraging these operators to take our programming skills to the next level.

FAQs
The bitwise operators in Python do operations at the bit level on integers; they become important when tasks such as those require efficient and precise control over binary data.
The bitwise AND operator compares each set of corresponding bits of two integers and returns a new integer with those bits set to 1 only if the corresponding bit of both integers is 1. It's useful for masking operations and setting specific bits to 0.
No, bitwise operators are primarily oriented at integer types. But, we can define our own behaviour for the bitwise operations in our classes by overloading the respective operators.
The left shift operator shifts the bits towards the left. It might be thought of as multiplying an integer by 2 to a power equal to the number of positions shifted. The right shift operator shifts the bits towards the right. It might be thought of as an integer division by 2 to a power equal to the number of positions shifted.
Bitwise operators allow for efficient manipulation of individual bits, making them useful for tasks like binary data manipulation, flag settings, and low-level data processing. They help optimise code by reducing the need for more complex arithmetic operations.

Updated on July 29, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

IIT Courses

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved