View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
python

Python Tutorials - Elevate You…

  • 199 Lessons
  • 33 Hours

Bitwise operators in Python

Updated on 22/01/20258,654 Views

Bitwise operators in Python manipulate individual bits of data. These operations are useful for low-level tasks like setting or clearing specific bits.

Many developers don’t use bitwise operators in Python, limiting their code optimization. Understanding these operators can make your code more efficient, especially for performance-critical applications.

In this article, we’ll explore bitwise operators in Python with examples, including the bitwise not operator in Python and how it works.

By the end, you will have a solid understanding of bitwise operations and how to use them effectively in your Python code.

“Enhance your Python skills further with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey!”

Bitwise Operators

Bitwise operators in Python manipulate individual bits of integers. They are useful for low-level operations and optimizing code for tasks like network programming or encryption.

Here’s an overview of Bitwise Operators

Operator

Symbol

Example (Output)

AND

&

4 & 5 = 4

OR

|

4 | 5 = 5

XOR

^

4 ^ 5 = 1

NOT

~

~4 = -5

AND Operator (&)

The AND operator compares each corresponding bit of two numbers. It returns 1 if both bits are 1; otherwise, it returns 0.

Example:

4 & 5

Output:

4

Explanation:

  • Binary of 4: 0100
  • Binary of 5: 0101
  • Performing 4 & 5: 0100 (result is 4), because both bits are 1 in the same positions for the first and third bit only.

Let’s look at another example:

Suppose you're working on a system where you need to quickly check if a number is even or odd.

In binary, even numbers have a 0 in the least significant bit (rightmost), while odd numbers have a 1 in that bit.

# check if the number is odd or even
number = 7
# use bitwise AND with 1 to check the least significant bit
if number & 1:
    print("Odd")
else:
    print("Even")

Output:

Odd

Explanation:

  • The expression number & 1 checks the least significant bit.
  • If the least significant bit is 1, the number is odd. If it's 0, the number is even.

This approach is faster than using modulus (%) for checking even or odd. The bitwise AND operator checks only the last bit, making it a compact and quick operation.

OR Operator (|)

The OR operator compares each corresponding bit of two numbers. It returns 1 if at least one bit is 1; otherwise, it returns 0.

Example:

4 | 5

Output:

5

Explanation:

  • Binary of 4: 0100
  • Binary of 5: 0101
  • Performing 4 | 5: 0101 (result is 5) because the second bit of 5 is 1, even though the first bit of 4 is 0.

Let’s look at another example:

Imagine you're building a system where users can have multiple permissions (read, write, execute), represented as individual bits.

You can use the bitwise OR operator to combine multiple permissions and grant a user more than one permission at once.

# define permissions (each permission is a separate bit)
READ = 0b001  #read permission
WRITE = 0b010  #write permission
EXECUTE = 0b100  #execute permission
# current user permissions (no permissions granted yet)
user_permissions = 0b000
# grant Read and Execute permissions to the user
new_permissions = user_permissions | READ | EXECUTE
# display new permissions in binary
print(bin(new_permissions))   

Output:

0b101

Explanation:

  • READ is 0b001, WRITE is 0b010, and EXECUTE is 0b100.
  • The bitwise OR (|) operator is used to combine Read and Execute permissions.
  • The result is 0b101, meaning the user now has both Read and Execute permissions.

Why Use Bitwise OR Here?

The OR operator lets you easily combine multiple permissions without affecting others. It allows you to handle permissions efficiently using a single integer.

XOR Operator (^)

The XOR operator compares the corresponding bits of two numbers and returns 1 if the bits are different; otherwise returns 0.

Example:

4 ^ 5

Output:

1

Explanation:

  • Binary of 4: 0100
  • Binary of 5: 0101
  • Performing 4 ^ 5: 0001 (result is 1), because the second bit of 4 is 0 and 5 has a 1 in the same position.

Let’s look at another example:

The XOR (exclusive OR) operator is commonly used to toggle specific bits in a number. When you perform XOR between two bits, it returns 1 if the bits are different and 0 if they are the same.

# initial value in binary
number = 0b101010  # binary: 42
# mask to toggle the 3rd bit (from the right)
mask_toggle = 0b00100  # mask for toggling the 3rd bit
# toggle the 3rd bit using XOR
number_toggled = number ^ mask_toggle
print(bin(number_toggled))  #output: 0b101110 (46)
# toggle the 3rd bit again (to revert back)
number_reverted = number_toggled ^ mask_toggle
print(bin(number_reverted))  # output: 0b101010 (42)

Output:

0b101110  0b101010

Explanation:

  • Toggle the 3rd bit: The bitwise XOR (^) operation is used to toggle the 3rd bit. If the 3rd bit is 1, it changes to 0, and if it’s 0, it changes to 1.
  • Reverting the toggle: XOR can be applied again with the same mask to revert the bit to its original state.

Why Use XOR Here?

  • It flips the bit’s value, making it easy to turn features on and off, such as in flag management or state tracking.
  • XOR is a fast, low-level operation, perfect for managing bits directly without complex logic.

NOT Operator (~)

The NOT operator inverts the bits of a number, changing 1 to 0 and 0 to 1. This is also known as bitwise negation.

Example:

~4

Output:

-5

Explanation:

  • Binary of 4: 0100
  • The NOT operator flips the bits to 1011.
  • The result is -5 because of Python’s two's complement representation for negative numbers.

Let’s look at another example:

Let’s say you're building a system that needs to quickly invert the sign of an integer, effectively converting a positive number to a negative one or vice versa.

# positive number
number = 10  # binary: 1010
# apply the bitwise NOT operator to invert the sign
inverted_number = ~number
print(inverted_number)  # output: -11
# apply bitwise NOT again to revert back to original number
original_number = ~inverted_number
print(original_number)  # output: 10

Output:

-11  # After applying bitwise NOT (negative version of the number)10   # After applying bitwise NOT again (back to original positive number)

Explanation:

  • The bitwise NOT operator in Python inverts all bits, including the sign bit. The result of ~10 is -11.
  • Applying the bitwise NOT again on the negative number brings us back to the original positive number.

Why Use Bitwise NOT Here?

  • You can use the bitwise NOT operator in Python for a quick and efficient solution instead of complex methods like arithmetic operations.
  • This method is commonly used in low-level programming or systems where performance matters, as it's a very fast operation.

“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”

Bitwise Shift Operators

Bitwise shift operators in Python allow you to shift the bits of a number left or right. These operators are commonly used to manipulate data efficiently at the bit level.

Operator

Symbol

Example (Output)

Left Shift

<<

4 << 1 = 8

Right Shift

>>

4 >> 1 = 2

Left Shift Operator (<<)

The Left Shift operator (<<) shifts the bits of a number to the left by a specified number of positions. Each left shift effectively multiplies the number by 2.

Example:

# number to shift
number = 4  #binary: 0100
# left shift by 1 position
result = number << 1
print(result)  #output: 8

Output:

8

Explanation:

  • In binary, 4 is 0100.
  • Shifting the bits of 4 to the left by one position results in 1000, which is 8.
  • This is equivalent to multiplying the number by 2^1.

Right Shift Operator (>>)

The Right Shift operator (>>) shifts the bits of a number to the right by a specified number of positions. Each right shift effectively divides the number by 2.

Example:

#number to shift
number = 4  #binary: 0100
#right shift by 1 position
result = number >> 1
print(result)  #output: 2

Output:

2

Explanation:

  • In binary, 4 is 0100.
  • Shifting the bits of 4 to the right by one position results in 0010, which is 2.
  • This is equivalent to dividing the number by 2^1.

Bitwise Operator Overloading

Bitwise operator overloading in Python allows you to define how bitwise operators like &, |, ^, <<, and >> behave when applied to objects of custom classes.

This allows you to extend the behavior of these operators beyond their default functionality for your own objects in Python, making it possible to integrate bitwise logic into custom data structures.

Let’s look at an example:

Suppose you’re designing a class in Python to represent a BitVector (a sequence of bits). You want to perform bitwise operations on instances of this class.

class BitVector:
    def __init__(self, value):
        self.value = value
    # Overloading the AND (&) operator
    def __and__(self, other):
        return BitVector(self.value & other.value)
    # Overloading the OR (|) operator
    def __or__(self, other):
        return BitVector(self.value | other.value)
    # Overloading the XOR (^) operator
    def __xor__(self, other):
        return BitVector(self.value ^ other.value)
    # Overloading the Left Shift (<<) operator
    def __lshift__(self, n):
        return BitVector(self.value << n)
    # Overloading the Right Shift (>>) operator
    def __rshift__(self, n):
        return BitVector(self.value >> n)
    def __repr__(self):
        return f'BitVector({bin(self.value)})'
# Create two BitVector instances
bv1 = BitVector(0b1101)  # Binary: 1101 (13 in decimal)
bv2 = BitVector(0b1011)  # Binary: 1011 (11 in decimal)
# Perform bitwise operations
result_and = bv1 & bv2
result_or = bv1 | bv2
result_xor = bv1 ^ bv2
result_lshift = bv1 << 2
result_rshift = bv2 >> 1
# Print results
print(result_and) 
print(result_or) 
print(result_xor) )
print(result_lshift) 
print(result_rshift) 

Output:

BitVector(0b1001)BitVector(0b1111)BitVector(0b110)BitVector(0b110100)BitVector(0b101)

Explanation:

  • Overloading Operators: In the class BitVector, we’ve overloaded the bitwise AND, OR, XOR, LEFT SHIFT, and RIGHT SHIFT operators. Each of these methods is defined with the corresponding special method name (e.g., __and__, __or__, __xor__, etc.).
  • Custom Behavior: The &, |, ^, <<, and >> operators are used as if they were applied to built-in Python integers, but now, they work with the custom BitVector class, allowing you to manipulate bit-level data within objects.

Why Use Bitwise Operator Overloading?

  • Overloading bitwise operators allows you to define custom behaviors for operators when working with your own objects. This is particularly useful when you’re working with custom data types that require bitwise manipulations (like bit vectors, flags, or masks).
  • By overloading operators, you can make your code more intuitive. Instead of calling a method like bitvector.and_operation(other), you can use the familiar & operator.

Pros and Cons

Pros:

  • Flexibility: You gain full control over how bitwise operations are performed on your custom objects.
  • Clean Syntax: Overloading makes your code look cleaner and more natural by using Python’s built-in operators.

Cons:

  • Complexity: If not used carefully overloading operators can make the code harder to understand. Too much overloading can lead to confusion, especially when operators are not intuitive for the data type.
  • Performance Overhead: Depending on how it's implemented, operator overloading may introduce a small performance overhead due to the additional method calls.

Practical Applications of Bitwise Operators

Let’s explore a few real-world uses where bitwise operators in Python with examples come into play.

1. Optimizing Performance

Bitwise operators can replace traditional arithmetic operations like multiplication or division by powers of two, making code faster and more efficient.

For example, instead of multiplying by 2, you can use left shift (<<) or divide by 2 using right shift (>>).

2. Network Programming

Bitwise operations are widely used in network programming to manage IP addresses and subnet masks.

For instance, AND (&) is used to check if an IP address belongs to a certain subnet. Similarly, OR (|) is used to combine subnet masks, and XOR (^) can be used to generate checksums or error detection codes.

Also Read: Computer Networking Basics: Network Types, Technologies, Topologies, Pros and Cons

3. Cryptography

Bitwise operators are fundamental in cryptography, especially in encryption and decryption algorithms.

The XOR operator is commonly used for simple encryption, where the same key is used to encrypt and decrypt data. Multiple bitwise operators like AND, OR, and XOR are often combined to create secure encryption schemes, such as the AES algorithm.

4. Flag Manipulation

Bitwise operators allow for efficient management of flags or settings in a single integer.

For example, bitwise OR (|) can be used to set a flag, bitwise AND (&) can clear a flag, and XOR (^) can toggle a flag. This is useful in system settings, role-based access control systems, or any application that requires managing multiple binary flags efficiently.

5. Image Processing

In image processing, bitwise operators are used to manipulate pixel data.

For example, AND can be used to mask specific regions of an image, while OR can be used to combine multiple images. XOR is used in various image manipulation algorithms to blend or extract information from multiple images.

Bitwise operations are often used to process images at the pixel level, which is important in fields like computer vision or graphics.

Also Read: Feature Extraction in Image Processing: Image Feature Extraction in ML

6. Compression Algorithms

Bitwise operations are widely used in data compression algorithms, such as Run-Length Encoding (RLE) and Huffman coding, where bitwise operators manipulate the bits to represent data efficiently. By using bitwise operators, you can reduce the amount of data stored or transmitted, which is critical in areas like file compression or network transmission.

7. Error Detection and Correction

In systems like cyclic redundancy checks (CRC), bitwise operations like XOR and AND are used to detect and correct errors in transmitted data.

For instance, XOR is used to generate checksums, and these can then be checked at the receiving end to verify data integrity.

8. Game Development

In game development, bitwise operators are used to manage multiple game states or properties efficiently.

For example, bitwise OR is used to enable features such as player abilities, while bitwise AND can be used to check which abilities are enabled. This allows developers to store and check multiple flags in a single integer, reducing memory usage.

By understanding and applying bitwise operators in Python with examples, you’ll be able to tackle problems that involve low-level data manipulation, optimize your code, and create more efficient systems.

FAQ's

1. What are bitwise operators in Python?

Bitwise operators in Python with examples are operators that perform bit-level operations on integers. They manipulate individual bits of numbers, providing efficient solutions for tasks like setting flags, encryption, and performance optimization.

2. What does the bitwise NOT operator in Python do?

The bitwise NOT operator in Python (~) inverts the bits of a number, turning all 1s into 0s and vice versa. It is typically used for bitwise negation or two's complement calculations.

3. Can you give an example of the bitwise AND operator in Python?

Yes! Bitwise AND (&) compares two numbers bit by bit. If both bits are 1, the result is 1; otherwise, it's 0. For example: 5 & 3 results in 1 because 101 & 011 = 001.

4. When would I use bitwise OR in Python?

Use bitwise OR (|) when you need to combine bits. It sets the corresponding result bit to 1 if any of the bits being compared is 1. For example, 5 | 3 results in 7.

5. How do bitwise operators help with performance?

Bitwise operators in Python with examples allow for faster operations than traditional arithmetic, especially when dealing with low-level tasks like shifting bits, setting flags, or handling binary data.

6. How does the bitwise NOT operator in Python affect signed numbers?

The bitwise NOT operator in Python affects signed numbers by converting them to their negative counterparts using two's complement representation. For instance, ~5 results in -6.

7. What’s the difference between bitwise AND and bitwise OR in Python?

Bitwise AND (&) only sets the result bit to 1 when both bits are 1, whereas bitwise OR (|) sets the result bit to 1 if at least one of the bits is 1.

8. How does the bitwise shift operator work in Python?

The bitwise shift operators (<< for left shift, >> for right shift) shift bits to the left or right by a specified number of positions. They are commonly used for multiplying or dividing numbers by powers of two.

9. What is the significance of the bitwise NOT operator in Python?

The bitwise NOT operator in Python is useful for inverting the binary representation of numbers, which is crucial in systems programming, encryption, and working with negative numbers in two's complement.

10. Can I use bitwise operators in Python for non-integer types?

No, bitwise operators in Python with examples only work on integer data types. If you need to manipulate non-integer types, consider converting them to integers first.

11. What are practical applications of bitwise operators in Python?

Bitwise operators in Python with examples are widely used for performance optimization, flag manipulation, networking (e.g., IP address checking), cryptography, and low-level system tasks such as error detection and correction.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
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.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.