0
0
PythonHow-ToBeginner · 4 min read

How to Use Bitwise Operators in Python: Syntax and Examples

In Python, bitwise operators like &, |, ^, ~, <<, and >> work on the binary form of integers to perform operations such as AND, OR, XOR, NOT, left shift, and right shift. You use them by placing the operator between or before integer values to manipulate bits directly.
📐

Syntax

Bitwise operators in Python work on integers at the bit level. Here are the main operators:

  • &: Bitwise AND
  • |: Bitwise OR
  • ^: Bitwise XOR (exclusive OR)
  • ~: Bitwise NOT (inverts bits)
  • <<: Left shift (shifts bits to the left)
  • >>: Right shift (shifts bits to the right)

You use them like normal operators between integers, for example: a & b or ~a.

python
a = 5  # binary 0101
b = 3  # binary 0011

and_result = a & b  # 0101 & 0011 = 0001 (1)
or_result = a | b   # 0101 | 0011 = 0111 (7)
xor_result = a ^ b  # 0101 ^ 0011 = 0110 (6)
not_result = ~a     # ~0101 = 1010 (in two's complement: -6)
left_shift = a << 1 # 0101 << 1 = 1010 (10)
right_shift = a >> 1 # 0101 >> 1 = 0010 (2)
💻

Example

This example shows how to use each bitwise operator on two numbers and prints the results.

python
a = 12  # binary 1100
b = 5   # binary 0101

print('a & b =', a & b)   # AND
print('a | b =', a | b)   # OR
print('a ^ b =', a ^ b)   # XOR
print('~a =', ~a)         # NOT
print('a << 2 =', a << 2) # Left shift by 2
print('a >> 2 =', a >> 2) # Right shift by 2
Output
a & b = 4 a | b = 13 a ^ b = 9 ~a = -13 a << 2 = 48 a >> 2 = 3
⚠️

Common Pitfalls

Common mistakes when using bitwise operators include:

  • Using bitwise operators on non-integers like floats or strings causes errors.
  • Confusing bitwise & with logical and, or bitwise | with logical or.
  • Not understanding that ~ returns the two's complement, which can be negative.
  • Shifting bits too far can lead to unexpected large or zero values.

Always ensure your values are integers and remember bitwise operators work on binary digits, not boolean logic.

python
x = 3.5
# print(x & 1)  # This will cause a TypeError because x is not an integer

# Correct usage:
x = 3
print(x & 1)  # Outputs 1
Output
1
📊

Quick Reference

OperatorDescriptionExampleResult
&Bitwise AND5 & 31
|Bitwise OR5 | 37
^Bitwise XOR5 ^ 36
~Bitwise NOT~5-6
<<Left shift5 << 110
>>Right shift5 >> 12

Key Takeaways

Bitwise operators work on the binary form of integers to manipulate individual bits.
Use & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), and >> (right shift) with integers only.
Avoid mixing bitwise operators with logical operators like and/or.
The ~ operator returns the two's complement, which can be negative.
Shifting bits changes the number by powers of two, so use shifts carefully.