Bytes
Data SciencePython

Bitwise Operators in Python

Last Updated: 24th November, 2024
icon

Arunav Goswami

Data Science Consultant at almaBetter

Learn about bitwise operators in Python, their types, usage, and examples, including bitwise XOR, AND, OR, NOT and shift operations for binary data manipulation

Bitwise operators are a critical feature of Python, enabling developers to manipulate data at the binary level. They perform operations on binary representations of integers and are particularly useful in low-level programming tasks such as system design, networking, and cryptography. This article explores bitwise operators in Python, their types, usage, and examples to provide a clear understanding.

What is Bitwise Operator in Python?

Bitwise operators in Python work directly with binary digits (bits) of integers. They execute operations bit-by-bit, leveraging the binary numbering system. The binary system uses two digits: 0 and 1, making bitwise operations faster and memory-efficient compared to higher-level operations. Python offers several bitwise operators, including AND, OR, XOR, NOT, and shifts, each serving distinct purposes in programming.

Types of Bitwise Operators in Python

Python provides six primary bitwise operators:

1. Bitwise AND (&)

  • Functionality: Performs a logical AND operation on corresponding bits of two numbers.
  • Result: A bit is set to 1 if both corresponding bits are 1; otherwise, it's 0.

Example:

a5       # Binary: 0101
b3       # Binary: 0011
result = a & b
print(result)  # Output: 1 (Binary: 0001)

2. Bitwise OR (|)

  • Functionality: Executes a logical OR operation on corresponding bits.
  • Result: A bit is set to 1 if either corresponding bit is 1.

Example:

a5       # Binary: 0101
b = 3       # Binary: 0011
result = a | b
print(result# Output: 7 (Binary: 0111)

3. Bitwise XOR (^)

  • Functionality: Executes an exclusive OR operation.
  • Result: A bit is set to 1 if corresponding bits are different.

Bitwise XOR in Python Example:

a5       # Binary: 0101
b = 3       # Binary: 0011
result = a ^ b
print(result# Output: 6 (Binary: 0110)

Applications:

  • Used in cryptography for encoding and decoding data.
  • Efficient for toggling specific bits.

4. Bitwise NOT (~)

  • Functionality: Inverts all bits of the operand.
  • Result: Converts 1 to 0 and 0 to 1. The output is represented in two's complement form.

Example:

a5       # Binary: 0101
result = ~a
print(result# Output: -6 (Binary: ...1010 in two's complement)

5. Bitwise Left Shift (<<)

  • Functionality: Shifts bits to the left by the specified number of positions.
  • Result: Each left shift operation multiplies the number by 2.

Example:

a5       # Binary: 0101
result = a << 2
print(result# Output: 20 (Binary: 10100)

6. Bitwise Right Shift (>>)

  • Functionality: Shifts bits to the right by the specified number of positions.
  • Result: Each right shift operation divides the number by 2, discarding the remainder.

Bitwise Right Shift Operator in Python Example:

a5       # Binary: 0101
result = a >> 2
print(result# Output: 1 (Binary: 0001)

Bitwise Operators in Python with Example

Combining Operations

Bitwise operators can be combined to achieve complex results. Consider the following example:

a12       # Binary: 1100
b25       # Binary: 11001

# Combining AND, OR, and XOR
and_result = a & b  # Binary: 1000 -> Decimal: 8
or_result = a | b   # Binary: 11101 -> Decimal: 29
xor_result = a ^ b  # Binary: 10101 -> Decimal: 21

print(and_result, or_result, xor_result)  # Outputs: 8, 29, 21

Using Bitwise Shifts for Multiplication and Division

a4   # Binary: 0100

# Left Shift by 1 (Multiply by 2)
left_shift = a << 1   # Binary: 1000 -> Decimal: 8

# Right Shift by 1 (Divide by 2)
right_shift = a >> 1  # Binary: 0010 -> Decimal: 2

print(left_shift, right_shift)  # Outputs: 8, 2

Bitwise Operator Overloading

Operator overloading allows operators to perform user-defined actions when applied to objects of custom classes. For bitwise operators, Python provides special methods (dunder methods) that correspond to these operations. By defining these methods within a class, developers can customize how the bitwise operators behave for objects of that class.

Common Dunder Methods for Bitwise Operators:

OperatorMethodExample Call
& (AND)__and__(self, other)obj1 & obj2
`` (OR)__or__(self, other)
^ (XOR)__xor__(self, other)obj1 ^ obj2
~ (NOT)__invert__(self)~obj1
<< (Left Shift)__lshift__(self, other)obj1 << value
>> (Right Shift)__rshift__(self, other)obj1 >> value

Implementing Bitwise Operator Overloading

Example 1: Overloading & and | for Custom Objects

class BitwiseExample:
    def __init__(self, value):
        self.value = value

    def __and__(self, other):
        return BitwiseExample(self.value & other.value)

    def __or__(self, other):
        return BitwiseExample(self.value | other.value)

    def __str__(self):
        return f"Value: {self.value}"

# Using the overloaded operators
obj1 = BitwiseExample(6# Binary: 0110
obj2 = BitwiseExample(3# Binary: 0011

and_result = obj1 & obj2  # Calls __and__()
or_result = obj1 | obj2   # Calls __or__()

print(and_result)  # Output: Value: 2 (Binary: 0010)
print(or_result)   # Output: Value: 7 (Binary: 0111)

Example 2: Overloading ^ (XOR) for Custom Logic

class BitwiseXorExample:
    def __init__(self, value):
        self.value = value

    def __xor__(self, other):
        return BitwiseXorExample(self.value ^ other.value)

    def __str__(self):
        return f"Value: {self.value}"

# Custom XOR operation
obj1 = BitwiseXorExample(5# Binary: 0101
obj2 = BitwiseXorExample(2# Binary: 0010

xor_result = obj1 ^ obj2  # Calls __xor__()
print(xor_result)  # Output: Value: 7 (Binary: 0111)

Applications of Bitwise Operators

1. Data Compression

  • Bitwise operations reduce data size by manipulating bits directly.
  • Example: Storing multiple boolean flags in a single byte.

2. Networking

  • Used in IP address manipulation and subnet calculations.
  • Example: Calculating the network address using bitwise AND.

3. Cryptography

  • The bitwise XOR operator is instrumental in encryption algorithms.
  • Example: Encoding a message:
message12       # Binary: 1100
key5            # Binary: 0101

# Encode
encoded = message ^ key  # Binary: 1001 -> Decimal: 9

# Decode
decoded = encoded ^ key  # Binary: 1100 -> Decimal: 12

print(encoded, decoded)  # Outputs: 9, 12

4. Control and Hardware Programming

  • Common in embedded systems for setting or clearing specific bits in control registers.

Boost your coding efficiency with our handy Python cheat sheet, explore tools like the Online Python compiler and dive deeper with our comprehensive Python tutorial!

Advantages and Limitations of Bitwise Operators

Advantages

  • Performance: Operates directly at the binary level, making operations faster.
  • Memory Efficiency: Saves space by working with bits instead of larger data structures.

Limitations

  • Readability: Bitwise operations can be challenging to understand and maintain.
  • Scope: Limited to integers, making them unsuitable for certain data types.

Best Practices for Using Bitwise Operators

  • Clarity: Add comments to explain complex bitwise operations.
  • Testing: Use test cases to ensure correct implementation, especially in critical systems.
  • Alternatives: Consider higher-level alternatives if readability is more critical than performance.

Conclusion

Python Bitwise operators are a powerful tool for binary data manipulation. From performing logical operations to enhancing encryption techniques, these operators are indispensable in programming tasks that require efficiency and precision. By understanding and practicing bitwise operations, developers can unlock advanced capabilities in Python, optimizing performance in various applications.

Master bitwise operations and more with our comprehensive data science course or take your skills further with a masters in data science program.

Related Articles

Top Tutorials

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2025 AlmaBetter