Lessons
Courses

Bitwise Operators in Python [ English ]

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:

  • Low-level programming
  • Optimizations
  • Data manipulation

2. Binary Representation

Before understanding bitwise operators, consider:

5 → 0101 3 → 0011

(All operations are performed bit by bit)

3. Types of Bitwise Operators

OperatorNameDescription
&ANDSets bit to 1 if both bits are 1
``ORSets bit to 1 if at least one bit is 1
^XORSets bit to 1 if bits are different
~NOTInverts all bits
<<Left ShiftShifts bits to the left
>>Right ShiftShifts bits to the right

4. Bitwise AND (&)

Example

a = 5 # 0101b = 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

  • ~n = -(n + 1)
  • So, ~5 = -6

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 # 0110b = 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

  • Works only with integers

  • Operates on binary values

  • ~ uses 2’s complement representation

  • Shifting:

    • << multiplies by 2
    • >> divides by 2

12. Summary

  • Bitwise operators work at the bit level.

  • Types include:

    • & (AND)
    • | (OR)
    • ^ (XOR)
    • ~ (NOT)
    • << (Left Shift)
    • >> (Right Shift)
  • Used in low-level operations and optimizations.

  • Understanding binary representation is essential.