Python Bitwise Operators: A Complete Guide with Real Examples and Use-Cases

1. What Are Python Bitwise Operators?

Python Bitwise operators perform operations directly on the binary representation of integers. They’re mainly used in areas like encryption, compression, graphics and system-level programming where performance and memory efficiency are crucial.

Python provides a clean syntax for working with these operators, making it easy to manipulate bits even in high-level code.

Note: For a complete overview of all Python operators including arithmetic, assignment, comparison, logical, bitwise and more, check out Complete Python Operators Guide.

1. Bitwise AND (&) Operator

Description:

The Bitwise AND (&) operator in Python compares two integers bit by bit and returns 1 only if both corresponding bits are 1.

It’s often used when working with binary data, permissions, or low-level operations such as masking specific bits.

Examples:

# Bitwise AND operation


a = 10 # Binary: 1010
b = 4  # Binary: 0100
result = a & b
print(result)  # 0 #Bitwise Evaluation: 1010 & 0100 = 0000 → Decimal 0

Use Case Example

Bitwise AND is widely used in permission handling or flag checking systems.

# Use Case: Checking permission using Bitwise AND


READ = 1   # 0001
WRITE = 2  # 0010
EXECUTE = 4 # 0100

#User has READ and EXECUTE permissions


user_permission = READ | EXECUTE  # 0001 | 0100 → 0101 (5)

# Check if WRITE permission is available

if user_permission & WRITE:
    print("Write allowed")
else:
    print("Write not allowed")

#Output:

Write not allowed

Real-Life Analogy:

Imagine you have two switches connected to a bulb — the light turns on only when both switches are ON. That’s exactly how the Bitwise AND operator works — both bits must be 1 to produce a 1.

Description:

The Bitwise OR (|) operator compares two integers bit by bit and returns 1 if at least one corresponding bit is 1.

It’s commonly used to combine flags, set bits, or enable multiple permissions in binary-based systems.

Examples:

#Example: Bitwise OR operation


a = 10  # Binary: 1010
b = 4   # Binary: 0100
result = a | b
print(result)  # 14 #Bitwise Evaluation: 1010 | 0100 = 1110 → Decimal 14

Explanation: The & operator checks if the WRITE bit (0010) is set in the user’s permission (0101). Since it’s not, access is denied.

Use Case Example

Bitwise OR is often used to combine multiple permission flags or set feature toggles.

#Use Case: Combining permissions with Bitwise OR


READ = 1    # 0001
WRITE = 2   # 0010
EXECUTE = 4 # 0100

# Grant READ and EXECUTE permissions


permission = READ | EXECUTE
print(permission)  # 5

#Output:
5
Explanation:

0001 | 0100 = 0101, which equals 5 in decimal. This means the user now has both READ and EXECUTE permissions combined.

Real-Life Analogy:

Think of two lamps controlled by separate switches but connected to the same power source — if either switch is ON, the light turns on.
Similarly, the Bitwise OR (|) operator activates a bit if either of the corresponding bits is 1.

Description:

The Bitwise XOR (^) operator (exclusive OR) compares each bit of two integers and returns 1 only when the bits are different — that is, one is 1 and the other is 0.

This operator is commonly used in encryption, toggling values, and parity checks because it flips bits in a predictable way.

Examples:

# Example: Bitwise XOR operation


a = 10  # Binary: 1010
b = 4   # Binary: 0100
result = a ^ b
print(result)  # 14

#Bitwise Evaluation:

1010 ^ 0100 = 1110 → Decimal 14
Explanation:

The XOR operator returns 1 when the bits differ. In this case:

  • Bit 3: 1 vs 0 → 1
  • Bit 2: 0 vs 1 → 1
  • Bit 1: 1 vs 0 → 1
  • Bit 0: 0 vs 0 → 0

So, the result is 1110 in binary, which equals 14 in decimal.

Use Case Example

Bitwise XOR is often used in encryption algorithms or flag toggling, as it can reverse changes when applied twice.


# Use Case: Simple data encryption using XOR


data = 42  # Original data
key = 12   # Encryption key

# Encrypt


encrypted = data ^ key
print("Encrypted:", encrypted)

# Decrypt (XORing again with the same key reverses the operation)


decrypted = encrypted ^ key
print("Decrypted:", decrypted)

#Output:
Encrypted: 38 
Decrypted: 42
Explanation:

The XOR operator is its own inverse — applying the same key twice restores the original value. This property makes it a lightweight technique for simple encryption or obfuscation.

Real-Life Analogy:

Think of Bitwise XOR as a toggle switch — if two switches are in opposite positions (one ON, one OFF), the light turns ON; if both are the same (both ON or both OFF), the light stays OFF. This makes XOR useful in scenarios where differences matter — like comparing or flipping data bits.

Description:

The Bitwise NOT (~) operator is a unary operator (acts on a single operand) that flips all bits of the number — converting every 1 to 0 and every 0 to 1.

In Python, this operation is known as taking the 1’s complement of a number.

For a positive integer n, the result of ~n is mathematically equal to -(n + 1).

Examples:

#Bitwise NOT operation


a = 10  # Binary: 1010
result = ~a
print(result)  # -11
Explanation:

~10 = -(10 + 1) = -11. When applying the NOT operator, Python treats numbers in signed binary representation (two’s complement form). That’s why the flipped bits represent a negative number.

Use Case Example

The Bitwise NOT operator is useful in:

  • Inverting binary masks
  • Turning ON/OFF bits in flag systems
  • Implementing complement operations in low-level computations

Example: Bitwise NOT in action for masking


mask = 0b1010  # 10 in binary
inverted_mask = ~mask
print("Mask:", mask)
print("Inverted Mask:", inverted_mask)

#Output:
Mask: 10
Inverted Mask: -11
Explanation:

Here, ~ flips all bits of the mask, creating a complementary (inverse) version of the bit pattern.

Technical Insight

In binary terms:

  • a = 0000 1010 → 10
  • ~a = 1111 0101 → -11

Python uses infinite-length integers, but conceptually, this mimics how negative numbers are represented in two’s complement form in most programming languages.

Real-Life Analogy:

Think of Bitwise NOT as an “opposite switch” — flipping ON to OFF and OFF to ON.

For instance, if a security system marks certain bits as “active sensors,” applying ~ would toggle all sensors: active ones become inactive, and inactive ones become active.

Description:

The Bitwise Left Shift (<<) operator shifts all bits of a number to the left by a specified number of positions.

Each left shift effectively multiplies the number by 2ⁿ, where n is the number of shifted positions.

New bits on the right are filled with zeros, ensuring that the value increases for positive integers.

Examples:

#Bitwise Left Shift


a = 5  # Binary: 0101
result = a << 1
print(result)  # 10
# Multiple left shifts
print(a << 2)  # 20
Explanation:
  • 0101 << 1 → 1010 → Decimal 10
  • 0101 << 2 → 10100 → Decimal 20

When shifting left:

  • Each bit moves one position to the left.
  • Zeros are added on the right side.
  • The number effectively doubles for each left shift.

Use Case Example

Bitwise left shifts are widely used in:

  • Performance optimization (faster multiplication by powers of two)
  • Graphics or image processing
  • Encoding/decoding bit flags or values

Example: Using left shift to calculate powers of two


for n in range(5):
    print(f"2 << {n} =", 2 << n)

#Output:

 

 

 

 

    • 2 << 0 = 21 = 4
    • 2 << 2 = 8

 

 

 

    • 2 << 3 = 16

 

 

 

    • 2 << 4 = 32

 

 


Explanation:

 

Each left shift multiplies the number by 2 — a fast and efficient way to compute powers of two using bitwise logic.

Real-Life Analogy:

Think of Bitwise Left Shift like moving a decimal point to the right in base-10 numbers.

For example, shifting 25 one place in base-10 gives 250.
Similarly, in binary, shifting left adds zeros at the end — amplifying the number’s value (like doubling or quadrupling it).

Technical Insight

Binary Representation:

  • a = 0000 0101 → 5
  • a << 1 = 0000 1010 → 10
  • a << 2 = 0001 0100 → 20

Every shift left doubles the number’s value — similar to multiplying by 2ⁿ.

 

Description:

The Bitwise Right Shift (>>) operator shifts all bits of a number to the right by a specified number of positions.

Each right shift effectively divides the number by 2ⁿ (ignoring remainders), where n is the number of shifted positions.

Bits on the right are discarded, and new bits on the left are filled based on the sign (0 for positive integers).

Examples:

#Bitwise Right Shift


a = 20  	# Binary: 10100
result = a >> 1
print(result)  # 10
# Multiple right shifts
print(a >> 2)  # 5
Explanation:
  • 10100 >> 1 → 01010 → Decimal 10
  • 10100 >> 2 → 00101 → Decimal 5

When shifting right:

  • Each bit moves one position to the right.
  • The rightmost bits are dropped.
  • The number effectively halves for each right shift.

Use Case Example

Bitwise right shift operations are commonly used in:

  • Performance optimizations (fast division by powers of two)
  • Compression algorithms
  • Binary data extraction or decoding
  • Bitmask operations

Example: Using right shift to divide by powers of two


for n in range(4):
    print(f"20 >> {n} =", 20 >> n)

#Output:
20 >>0 = 20 
20 >>1 = 10 
20 >> 2 = 5 
20 >> 3 = 2
Explanation:

Each right shift divides the number by 2ⁿ, discarding any fractional part (similar to floor division).

Real-Life Analogy:

Imagine cutting a number in half every time you shift it right. For instance, shifting 20 once gives 10, and shifting again gives 5. It’s similar to dividing by 2 repeatedly — but done at the binary level, which makes it much faster for computers.

Technical Insight

Binary Representation: /p>

  • a = 0001 0100 → 20
  • a >> 1 = 0000 1010 → 10
  • a >> 2 = 0000 0101 → 5

Each shift right moves bits one place lower — halving the number every time.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top