Bitwise Operators

4 min read ·

Bitwise operators in Python are used to perform operations at the binary (bit) level. They work on integers by converting them into binary representation, applying the operation, and returning the result as an integer.
Bitwise operators are commonly used in:
  • Low-level programming
  • Performance optimization
  • Networking and cryptography
  • Flags and permissions

What Are Bitwise Operators?

Bitwise operators operate on individual bits of integers.
Example:

Bitwise Operators Table

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

Bitwise AND (&)

Compares each bit of two numbers.
Explanation:
0101 0011 ---- 0001 -> 1

Bitwise OR (|)

Sets a bit if any one bit is 1.
Explanation:
0101 0011 ---- 0111 -> 7

Bitwise XOR (^)

Sets a bit if bits are different.
Explanation:
0101 0011 ---- 0110 -> 6

Bitwise NOT (~)

Inverts all bits.
Explanation:
~0101 = -(5 + 1) = -6

Bitwise Left Shift (<<)

Shifts bits to the left (multiplies by powers of 2).
Explanation:
5 << 1 = 10 5 << 2 = 20

Bitwise Right Shift (>>)

Shifts bits to the right (divides by powers of 2).
Explanation:
20 >> 1 = 10 20 >> 2 = 5

Bitwise Operators with Assignment


Bitwise Operators vs Logical Operators

Bitwise OperatorsLogical Operators
Works on bitsWorks on Boolean values
Uses &, |, ^, ~Uses and, or, not
No short-circuitingSupports short-circuiting
Operates on integersOperates on Boolean expressions
Used in low-level operationsUsed in conditional logic

Common Use Case: Flags


Common Mistakes

Confusing Logical and Bitwise Operators

Correct:

Practice

  • Convert numbers to binary and apply bitwise operators
  • Use shift operators to multiply and divide
  • Create a simple permission system using bitwise operators
  • Compare logical and bitwise behavior