Notes
Categories

Bitwise Operators in Python [ English ]

< Prev Next >

1. Introduction

Bitwise operators are used to perform operations on binary (bit-level) representations of integers. These operators work directly on the bits (0s and 1s) of numbers.

They are mainly used in:

2. Binary Representation

Before understanding bitwise operators, consider:

5  →  0101  
3  →  0011

(All operations are performed bit by bit)

3. Types of Bitwise Operators

Operator Name Description
& AND Sets bit to 1 if both bits are 1
` ` OR Sets bit to 1 if at least one bit is 1
^ XOR Sets bit to 1 if bits are different
~ NOT Inverts all bits
<< Left Shift Shifts bits to the left
>> Right Shift Shifts bits to the right

4. Bitwise AND (&)

Example

a = 5   # 0101
b = 3   # 0011

print(a & b)

Output

1

Explanation

  0101
& 0011
------
  0001  → 1

5. Bitwise OR (|)

print(5 | 3)

Output

7

Explanation

  0101
| 0011
------
  0111 → 7

6. Bitwise XOR (^)

print(5 ^ 3)

Output

6

Explanation

  0101
^ 0011
------
  0110 → 6

7. Bitwise NOT (~)

print(~5)

Output

-6

Explanation

8. Left Shift (<<)

Shifts bits to the left.

print(5 << 1)

Output

10

Explanation

5 → 0101  
Shift left → 1010 → 10

👉 Equivalent to multiplying by 2

9. Right Shift (>>)

Shifts bits to the right.

print(5 >> 1)

Output

2

Explanation

5 → 0101  
Shift right → 0010 → 2

👉 Equivalent to dividing by 2

10. Practical Example

a = 6   # 0110
b = 2   # 0010

print("AND:", a & b)
print("OR:", a | b)
print("XOR:", a ^ b)
print("Left Shift:", a << 1)
print("Right Shift:", a >> 1)

11. Important Points

12. Summary

< Prev Next >