Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

🐍 Python – Bitwise Operators (Complete Beginner Guide)

Python provides bitwise operators that work directly on the binary representation of numbers. These operators are mainly used in low-level programming, performance optimization, and working with binary data.

In this post, we will learn Python Bitwise Operators in detail with examples.


🧠 What are Bitwise Operators?

Bitwise operators perform operations on numbers at the bit (binary) level.

👉 In simple words:

  • Computers store data in binary (0 and 1)
  • Bitwise operators manipulate these bits directly

⚙️ Types of Python Bitwise Operators

Python supports the following bitwise operators:


& 1. Bitwise AND (&)

Compares each bit and returns 1 only if both bits are 1.

Example:

a = 5   # 0101
b = 3 # 0011

print(a & b)

Output:

1

| 2. Bitwise OR (|)

Returns 1 if at least one bit is 1.

Example:

a = 5   # 0101
b = 3 # 0011

print(a | b)

^ 3. Bitwise XOR (^)

Returns 1 if bits are different.

Example:

a = 5   # 0101
b = 3 # 0011

print(a ^ b)

~ 4. Bitwise NOT (~)

Inverts all bits (0 becomes 1, 1 becomes 0).

Example:

a = 5

print(~a)

<< 5. Left Shift (<<)

Shifts bits to the left (multiplies by 2).

Example:

a = 5

print(a << 1)

>> 6. Right Shift (>>)

Shifts bits to the right (divides by 2).

Example:

a = 5

print(a >> 1)

🧪 Bitwise Example with Binary View

a = 5   # 0101
b = 3 # 0011

print("AND:", a & b)
print("OR:", a | b)
print("XOR:", a ^ b)

📊 Python Bitwise Operators Summary

OperatorNameDescription
&    AND             Both bits must be 1
             OR
^    XOR             Bits must be different
~    NOT             Inverts bits
<<    Left Shift             Multiply by 2
>>    Right Shift             Divide by 2

🚀 Where Bitwise Operators are Used?

Bitwise operators are used in:

  • System programming ⚙️
  • Cryptography 🔐
  • Image processing 🖼️
  • Compression algorithms 📦
  • Hardware-level programming 💻

🧾 Conclusion

Python bitwise operators work at the binary level and are very powerful for advanced programming tasks involving performance and low-level operations.


💡 Final Thought

If you understand bitwise operations, you gain deeper control over how data is processed inside a computer.




Post a Comment

0 Comments