βš™οΈ Python Bitwise Operators β€” Working at the Binary Level

Introduction 🌟

Bitwise operators allow you to work with numbers at the **binary level**. They are extremely useful in low-level programming, optimization, encryption, networking, and performance-critical tasks.

Note

πŸ’‘ Bitwise operations work on the binary representation of integers (0s and 1s).

1. List of Bitwise Operators πŸ“‹

OperatorSymbolDescriptionExample
AND&Sets bit to 1 if both bits are 15 & 3
OR|Sets bit to 1 if any bit is 15 | 3
XOR^Sets bit to 1 if bits are different5 ^ 3
NOT~Flips all bits~5
Left Shift<<Shifts bits left, filling with 0s5 << 1
Right Shift>>Shifts bits right5 >> 1

2. Understanding Binary Representation πŸ”’

binary.py

print(bin(5))   # 0b101
print(bin(3))   # 0b011

5 = 101 (binary)3 = 011 (binary)

3. Bitwise AND (&) 🟩

Returns 1 only if both bits are 1.

and_op.py

print(5 & 3)      # 1
print(bin(5 & 3))  # 0b1

Note

Explanation: 101 & 011 β†’ 001 (binary) β†’ 1

4. Bitwise OR (|) 🟦

Returns 1 if any bit is 1.

or_op.py

print(5 | 3)      # 7
print(bin(5 | 3))  # 0b111

Note

Explanation: 101 | 011 β†’ 111 (binary) β†’ 7

5. Bitwise XOR (^) 🟨

Returns 1 only if bits are different.

xor_op.py

print(5 ^ 3)      # 6
print(bin(5 ^ 3))  # 0b110

Note

Explanation: 101 ^ 011 β†’ 110 (binary) β†’ 6

6. Bitwise NOT (~) πŸ”„

Flips all bits β€” also known as 1’s complement.

not_op.py

print(~5)      # -6

Note

🧠 Formula: ~x = -(x + 1)Example: ~5 = -(5 + 1) = -6

7. Left Shift (<<) ⬅️

Shifts bits to the left β€” adds zeros at the end.

left_shift.py

print(5 << 1)    # 10
print(bin(5 << 1)) # 0b1010

Note

Shifts 101 β†’ 1010 (binary)

8. Right Shift (>>) ➑️

Shifts bits to the right β€” drops rightmost bit.

right_shift.py

print(5 >> 1)    # 2
print(bin(5 >> 1)) # 0b10

Note

Shifts 101 β†’ 10 (binary)

9. Bitwise Operators With Variables 🎯

variables_bitwise.py

x = 12   # 1100
y = 10   # 1010

print(x & y)  # 1000 -> 8
print(x | y)  # 1110 -> 14
print(x ^ y)  # 0110 -> 6

10. Useful Real-World Examples 🌍

Check If a Number Is Even or Odd

even_odd.py

num = int(input("Enter a number: "))

if num & 1 == 0:
    print("Even")
else:
    print("Odd")

Swapping Two Numbers Without Temporary Variable

swap.py

a = 5
b = 3

a = a ^ b
b = a ^ b
a = a ^ b

print(a, b)

Bit Masking Example

bitmask.py

permissions = 0b1010  # read + write
mask = 0b0010        # check write permission

if permissions & mask:
    print("Write allowed")
else:
    print("Write denied")

Conclusion πŸŽ‰

>>β€œBitwise operators unlock Python’s low-level power β€” perfect for optimization and binary operations.” ⚑

You now understand all bitwise operators with examples and real-world use cases. Want the next topic? Try Conditional Statements, Loops, Expressions, or Control Flow. Just tell me! 😊