Python Bitwise Operators

Python bitwise operators are used to perform bitwise calculations on integers. The integers are converted into binary format and then operations are performed bit by bit, hence the name bitwise operators. Python bitwise operators work on integers only and the final output is returned in the decimal format. Python bitwise operators are also called binary operators.

Types of Python Bitwise Operators

There are 6 bitwise operators in Python. The below table provides short details about them.

Bitwise Operator Description Simple Example
& Bitwise AND Operator 10 & 7 = 2
| Bitwise OR Operator 10 | 7 = 15
^ Bitwise XOR Operator 10 ^ 7 = 13
~ Bitwise Ones’ Compliment Operator ~10 = -11
<< Bitwise Left Shift operator 10<<2 = 40
>> Bitwise Right Shift Operator 10>>1 = 5

Let’s look into these operators one by one and understand how they work.

1. Bitwise AND Operator

Python bitwise and operator returns 1 if both the bits are 1, otherwise 0.

2. Bitwise OR Operator

Python bitwise or operator returns 1 if any of the bits is 1. If both the bits are 0, then it returns 0.

3. Bitwise XOR Operator

Python bitwise XOR operator returns 1 if one of the bits is 0 and the other bit is 1. If both the bits are 0 or 1, then it returns 0.

4. Bitwise Ones’ Complement Operator

Python Ones’ complement of a number ‘A’ is equal to -(A+1).

>>> ~10
-11
>>> ~-10
9
>>>

5. Bitwise Left Shift Operator

Python bitwise left shift operator shifts the left operand bits towards the left side for the given number of times in the right operand. In simple terms, the binary number is appended with 0s at the end.

6. Bitwise Right Shift Operator

Python right shift operator is exactly the opposite of the left shift operator. Then left side operand bits are moved towards the right side for the given number of times. In simple terms, the right side bits are removed.

Python Bitwise Operator Overloading

Python supports operator overloading. There are various methods that we can implement to support bitwise operators for our custom objects.

Bitwise Operator Method to Implement
& __and__(self, other)
^ __xor__(self, other)
~ __invert__(self)
<< __lshift__(self, other)
>> __rshift__(self, other)

Here is an example of a bitwise operator overloading for our custom object.

class Data:
    id = 0

    def __init__(self, i):
        self.id = i

    def __and__(self, other):
        print('Bitwise AND operator overloaded')
        if isinstance(other, Data):
            return Data(self.id & other.id)
        else:
            raise ValueError('Argument must be object of Data')

    def __or__(self, other):
        print('Bitwise OR operator overloaded')
        if isinstance(other, Data):
            return Data(self.id | other.id)
        else:
            raise ValueError('Argument must be object of Data')

    def __xor__(self, other):
        print('Bitwise XOR operator overloaded')
        if isinstance(other, Data):
            return Data(self.id ^ other.id)
        else:
            raise ValueError('Argument must be object of Data')

    def __lshift__(self, other):
        print('Bitwise Left Shift operator overloaded')
        if isinstance(other, int):
            return Data(self.id << other) else: raise ValueError('Argument must be integer') def __rshift__(self, other): print('Bitwise Right Shift operator overloaded') if isinstance(other, int): return Data(self.id >> other)
        else:
            raise ValueError('Argument must be integer')

    def __invert__(self):
        print('Bitwise Ones Complement operator overloaded')
        return Data(~self.id)

    def __str__(self):
        return f'Data[{self.id}]'


d1 = Data(10)
d2 = Data(7)

print(f'd1&d2 = {d1&d2}')
print(f'd1|d2 = {d1|d2}')
print(f'd1^d2 = {d1^d2}')
print(f'd1<<2 = {d1<<2}') print(f'd1>>2 = {d1>>2}')
print(f'~d1 = {~d1}')

Output:

Bitwise AND operator overloaded
d1&d2 = Data[2]
Bitwise OR operator overloaded
d1|d2 = Data[15]
Bitwise XOR operator overloaded
d1^d2 = Data[13]
Bitwise Left Shift operator overloaded
d1<<2 = Data[40] Bitwise Right Shift operator overloaded d1>>2 = Data[2]
Bitwise Ones Complement operator overloaded
~d1 = Data[-11]

Error Handling in Bitwise Operators in Python

When working with bitwise operators in Python, various errors can occur that may impact the functionality of your code. Proper error handling is essential to ensure the robustness and reliability of your programs.

Common Error Sources:

  1. Incorrect Operand Types:
    Bitwise operators expect integer operands. If other data types such as floating-point numbers or strings are used instead, a TypeError will be raised.
  2. Overflow in Shift Operations:
    In left or right shift operations, an overflow can occur if the number of shift positions exceeds the bit length of the operand.
  3. Unintended Negative Results:
    The use of the bitwise NOT operator (~) can lead to negative numbers, as it inverts all bits, including the sign bit.

Recommendations for Avoiding Errors:

  • Type Checking:
    Ensure that the operands are of the expected data types before performing bitwise operations. The isinstance() function can be used for this.
  • Consider Limits:
    When using shift operations, make sure the number of shift positions stays within the valid range to avoid overflows.
  • Verify Results:
    After applying bitwise operators, check the results for plausibility, especially if negative values are undesirable.

Example of Error Handling:

def safe_bitwise_and(a, b):
if not isinstance(a, int) or not isinstance(b, int):
raise TypeError(“Both operands must be integers.”)
return a & b

try:
result = safe_bitwise_and(10, ‘7’)
except TypeError as e:
print(f”Error: {e}”)

In this example, before performing the bitwise AND operation, we check whether both operands are integers. If they are not, a TypeError is raised, which is caught and handled in the try-except block.

By implementing such checks and carefully handling potential error sources, you can improve the reliability and stability of your Python programs.

Summary

Python bitwise operators are mostly used in mathematical calculations. We can implement specific methods to support bitwise operators for our custom class implementations too.

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in: