Bitwise Operators in Python: A Complete Guide with Examples

Bitwise Operators in Python: A Complete Guide with Examples

Bitwise operators in Python allow direct manipulation of bits within an integer. These operators are useful in low-level programming, optimization, and working with binary data. In this blog, we will cover different bitwise operations and their practical use cases.

What Are Bitwise Operators?

Bitwise operators perform operations at the binary level. In Python, integers are represented in binary, making bitwise operations an efficient way to manipulate data.

Types of Bitwise Operators in Python

1. Bitwise AND (&)

The bitwise AND operator compares each bit of two numbers and returns 1 if both bits are 1, otherwise 0.

x = 5  # 101 in binary
y = 3  # 011 in binary
result = x & y  # 001 (1 in decimal)
print(result)  # Output: 1

2. Bitwise OR (|)

The OR operator returns 1 if at least one of the corresponding bits is 1.

x = 5  # 101
y = 3  # 011
result = x | y  # 111 (7 in decimal)
print(result)  # Output: 7

3. Bitwise XOR (^)

The XOR operator returns 1 if the bits are different, else 0.

x = 5  # 101
y = 3  # 011
result = x ^ y  # 110 (6 in decimal)
print(result)  # Output: 6

4. Bitwise NOT (~)

The NOT operator inverts the bits (flips 1 to 0 and vice versa) and returns the two's complement of the number.

x = 5  # 00000101
result = ~x  # 11111010 (-6 in decimal due to two's complement representation)
print(result)  # Output: -6

5. Left Shift (<<)

The left shift operator moves bits to the left by a specified number of positions, filling the empty spaces with 0s.

x = 5  # 101
result = x << 2  # 10100 (20 in decimal)
print(result)  # Output: 20

6. Right Shift (>>)

The right shift operator moves bits to the right, discarding shifted bits.

x = 20  # 10100
result = x >> 2  # 101 (5 in decimal)
print(result)  # Output: 5

Practical Applications of Bitwise Operators

  1. Checking if a Number is Even or Odd:

def is_even(n):
    return (n & 1) == 0

print(is_even(4))  # Output: True
print(is_even(7))  # Output: False
  1. Swapping Two Numbers Without a Temporary Variable:

a = 5
b = 7
a = a ^ b
b = a ^ b
a = a ^ b
print(a, b)  # Output: 7 5
  1. Finding the Unique Element in a List Where All Others Appear Twice:

def find_unique(arr):
    result = 0
    for num in arr:
        result ^= num
    return result

print(find_unique([2, 3, 5, 3, 2]))  # Output: 5

Conclusion

Bitwise operators in Python provide a powerful way to optimize code by directly manipulating binary representations. They are widely used in cryptography, data compression, low-level programming, and game development. By mastering these operators, you can improve your problem-solving skills and write more efficient programs.