Python Bitwise Operators

1. What are Bitwise Operators?

Bitwise operators work with binary numbers (0 and 1).

In simple words:
👉 They work on bits, not normal numbers.

These operators are mostly used in:

  • Low-level programming

  • Performance-related code

  • Special calculations

Beginners should just understand the idea.

2. Binary Numbers (Very Simple)

Binary uses only:

  • 0

  • 1

Example:

  • 5 in binary = 101

  • 3 in binary = 011

3. List of Bitwise Operators

Operator Name Meaning
& AND Both bits must be 1
OR
^ XOR Bits are different
~ NOT Reverse bits
<< Left Shift Move bits left
>> Right Shift Move bits right

4. Bitwise AND (&)

& compares bits and returns 1 only if both bits are 1.

Example

a = 5 # 101
b = 3 # 011

print(a & b)

Output:

1

5. Bitwise OR (|)

| returns 1 if any bit is 1.

Example

print(a | b)

Output:

7

6. Bitwise XOR (^)

^ returns 1 if bits are different.

Example

print(a ^ b)

Output:

6

7. Bitwise NOT (~)

~ reverses bits.

Example

x = 5
print(~x)

Output:

-6

👉 Result is negative because of Python’s internal system.

8. Bitwise Left Shift (<<)

Moves bits to the left.

Example

x = 5
print(x << 1)

Output:

10

Explanation

5 << 1 means:

  • Multiply by 2

9. Bitwise Right Shift (>>)

Moves bits to the right.

Example

x = 10
print(x >> 1)

Output:

5

Explanation

10 >> 1 means:

  • Divide by 2

10. Simple Real-Life Understanding

Operation Effect
<< 1 Multiply by 2
>> 1 Divide by 2

11. Common Beginner Mistakes

❌ Confusing Logical and Bitwise

a and b # logical
a & b # bitwise

They are not the same.

❌ Expecting Normal Math

print(5 & 3) # not 15

12. Simple Practice Examples

Example 1: Check Even or Odd

num = 4
print(num & 1)

Output:

0

Example 2: Double a Number

x = 7
print(x << 1)

Example 3: Half a Number

x = 8
print(x >> 1)

13. Summary (Bitwise Operators)

✔ Work with binary (0,1)
✔ Used for special tasks
& | ^ ~ << >> are bitwise operators
<< doubles number
>> halves number

📘 Perfect for Beginner eBook

This chapter is ideal for:

  • Python beginner books

  • Students who want basics

  • Self-learners

If you want next, I can write:

  • Python Operator Exercises

  • if–else statements

  • Loops (for, while)

  • MCQs with answers

Just tell me 😊

You may also like...