VOOZH about

URL: https://www.analyticsvidhya.com/blog/2024/02/bitwise-operators-in-python/

⇱ Bitwise Operators in Python - Analytics Vidhya


India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder

  • d
  • :
  • h
  • :
  • m
  • :
  • s

6 Major Bitwise Operators in Python

Himanshu Pathak Last Updated : 03 Apr, 2024
5 min read

Introduction

Bitwise operators are essential to Python programming, allowing you to manipulate individual bits of an integer. Understanding how to use these operators can significantly enhance your programming skills and open up new possibilities for solving complex problems. In addition, mastering bitwise operators is crucial for tasks such as low-level programming, optimization, and implementing specific algorithms where direct bit manipulation is a fundamental requirement. This article will explore the basics of bitwise operators in Python and provide examples to demonstrate their practical applications.

What are Bitwise Operators?

Bitwise operators are used to perform operations at the bit level. In the following topic Python bitwise operators are available:

  1. AND
  2. OR
  3. XOR
  4. NOT
  5. Left Shift
  6. Right Shift

Each of these operators has a specific function and can be used to perform different types of bit-level manipulations. To understand their work, let’s examine each of these operators in more detail.

6 Major Python Bitwise Operators

AND Operator

The AND operator returns 1 for each bit position where both operands have 1. Otherwise, it returns 0. This operator is often used to clear specific bits in an integer. Here’s an example of using the AND operator in Python:

Example

a = 60  # 60 = 0011 1100
b = 13  # 13 = 0000 1101
c = a & b  # 12 = 0000 1100
print("Result of AND operation:", c)

Output

Result of AND operation: 12

OR Operator

The OR operator returns 1 for each bit position where at least one operand has 1. It returns 0 only if both operands have 0. This operator is commonly used to set specific bits in an integer. Here’s an example of using the OR operator in Python:

Example

a = 60  # 60 = 0011 1100
b = 13  # 13 = 0000 1101
c = a | b  # 61 = 0011 1101
print("Result of OR operation:", c)

Output

Result of OR operation: 61

XOR Operator

The XOR operator returns 1 for each bit position where the operands have different bits. It returns 0 if both bits are the same. This operator is useful for flipping the bits of an integer. Here’s an example of using the XOR operator in Python:

Example

a = 60  # 60 = 0011 1100
b = 13  # 13 = 0000 1101
c = a ^ b  # 49 = 0011 0001
print("Result of XOR operation:", c)

Output

Result of XOR operation: 49

NOT Operator

The NOT operator returns the complement of the operand, i.e., it changes each 1 to 0 and each 0 to 1. This operator is often used to reverse the bits of an integer. Here’s an example of using the NOT operator in Python:

Example

a = 60  # 60 = 0011 1100
c = ~a  # -61 = 1100 0011
print("Result of NOT operation:", c)

Output

Result of NOT operation: -61

Left Shift Operator

The left shift operator moves the bits of the operand to the left by a specified number of positions. This effectively multiplies the operand by 2, raised to the power of the shift count. Here’s an example of using the left shift operator in Python:

Example

a = 60  # 60 = 0011 1100
b = a << 2  # 240 = 1111 0000
print("Result of left shift operation:", b)

Output

Result of left shift operation: 240

Right Shift Operator

The right shift operator moves the operand bits to the right by a specified number of positions. This effectively divides the operand by 2, raised to the power of the shift count. Here’s an example of using the right shift operator in Python:

Example

a = 60  # 60 = 0011 1100
b = a >> 2  # 15 = 0000 1111
print("Result of right shift operation:", b)

Output

Result of right shift operation: 15

Practical Applications of Bitwise Operators in Data Science

Even though they’re usually seen as basic tools, bitwise operators are surprisingly useful for different tasks in data science. Here are some real-world examples of how they can be handy:

  1. Efficient Feature Engineering: Simplify creating features from data using simple math tricks to extract information like time or categories and combine or shrink these categories for easier use.
  1. Data Cleaning and Manipulation: Check and adjust your data types, handle missing pieces of information cleverly, and organize data better to save space and make it faster to work with.
  1. Image Processing and Computer Vision: Use basic math operations to tweak and analyze images, like changing specific parts of an image or combining images to highlight changes or detect edges.
  1. Machine Learning and Optimization: Simplify the math behind predictive models or decisions to create smarter models, especially for small, resource-limited devices, and make some operations faster and more efficient.
  1. Cryptography and Security: Protecting information by mixing it with a secret key or checking data hasn’t been tampered with using simple coding tricks for basic safety measures.

Bitwise Operator Overloading

In Python, bitwise operators let you work with binary data on a low level. You can use these operators to perform operations like AND, OR, XOR, and NOT on binary numbers.

Here are the bitwise operators in Python:

  • & (AND): Sets each bit to 1 if both bits are 1.
  • | (OR): Sets each bit to 1 if at least one of the bits is 1.
  • ^ (XOR): Sets each bit to 1 if only one of the bits is 1.
  • ~ (NOT): Flips all the bits.

For example:

# Bitwise AND
result = 5 & 3 # Output: 1
print(result)

# Bitwise OR
result = 5 | 3 # Output: 7
print(result)

# Bitwise XOR
result = 5 ^ 3 # Output: 6
print(result)

# Bitwise NOT
result = ~5 # Output: -6
print(result)

Conclusion

In this article, we’ve explored the fundamentals of bitwise operators in Python and provided examples to illustrate their usage. By mastering these operators, you can better understand how data is represented at the bit level and leverage this knowledge to write more efficient and optimized code. Whether you’re working on low-level programming or tackling complex algorithms, bitwise operators are a powerful tool with which every Python programmer should be familiar. So, experiment with these operators to unlock their full potential in your Python projects.

Frequently Asked Questions

Q1. What is the bitwise complement in Python?

The bitwise complement (~) in Python flips all the bits in a binary number. So if a bit is 0, it becomes 1, and if it’s 1, it becomes 0.

Q2.What is == and != in Python?

In Python, == checks if two things are the same, like comparing if two numbers are equal. != checks if two things are different. For example, 5 == 5 is True, but 5 != 6 is also True.

Q3. What is === in Python?

In Python, there’s no === operator. It’s used in some other languages, but not in Python.

Q4.What is double == in Python?

In Python, double == is used to compare if two things are equal. For example, 5 == 5 is True, but 5 == 6 is False.

If you are looking for Python online course, then explore: Learn Python for Data Science.

Login to continue reading and enjoy expert-curated content.

Free Courses

Generative AI - A Way of Life

Explore Generative AI for beginners: create text and images, use top AI tools, learn practical skills, and ethics.

Getting Started with Large Language Models

Master Large Language Models (LLMs) with this course, offering clear guidance in NLP and model training made simple.

Building LLM Applications using Prompt Engineering

This free course guides you on building LLM apps, mastering prompt engineering, and developing chatbots with enterprise data.

Improving Real World RAG Systems: Key Challenges & Practical Solutions

Explore practical solutions, advanced retrieval strategies, and agentic RAG systems to improve context, relevance, and accuracy in AI-driven applications.

Microsoft Excel: Formulas & Functions

Master MS Excel for data analysis with key formulas, functions, and LookUp tools in this comprehensive course.

Responses From Readers

Flagship Programs

GenAI Pinnacle Program| GenAI Pinnacle Plus Program| AI/ML BlackBelt Program| Agentic AI Pioneer Program

Free Courses

Generative AI| DeepSeek| OpenAI Agent SDK| LLM Applications using Prompt Engineering| DeepSeek from Scratch| Stability.AI| SSM & MAMBA| RAG Systems using LlamaIndex| Building LLMs for Code| Python| Microsoft Excel| Machine Learning| Deep Learning| Mastering Multimodal RAG| Introduction to Transformer Model| Bagging & Boosting| Loan Prediction| Time Series Forecasting| Tableau| Business Analytics| Vibe Coding in Windsurf| Model Deployment using FastAPI| Building Data Analyst AI Agent| Getting started with OpenAI o3-mini| Introduction to Transformers and Attention Mechanisms

Popular Categories

AI Agents| Generative AI| Prompt Engineering| Generative AI Application| News| Technical Guides| AI Tools| Interview Preparation| Research Papers| Success Stories| Quiz| Use Cases| Listicles

Generative AI Tools and Techniques

GANs| VAEs| Transformers| StyleGAN| Pix2Pix| Autoencoders| GPT| BERT| Word2Vec| LSTM| Attention Mechanisms| Diffusion Models| LLMs| SLMs| Encoder Decoder Models| Prompt Engineering| LangChain| LlamaIndex| RAG| Fine-tuning| LangChain AI Agent| Multimodal Models| RNNs| DCGAN| ProGAN| Text-to-Image Models| DDPM| Document Question Answering| Imagen| T5 (Text-to-Text Transfer Transformer)| Seq2seq Models| WaveNet| Attention Is All You Need (Transformer Architecture) | WindSurf| Cursor

Popular GenAI Models

Llama 4| Llama 3.1| GPT 4.5| GPT 4.1| GPT 4o| o3-mini| Sora| DeepSeek R1| DeepSeek V3| Janus Pro| Veo 2| Gemini 2.5 Pro| Gemini 2.0| Gemma 3| Claude Sonnet 3.7| Claude 3.5 Sonnet| Phi 4| Phi 3.5| Mistral Small 3.1| Mistral NeMo| Mistral-7b| Bedrock| Vertex AI| Qwen QwQ 32B| Qwen 2| Qwen 2.5 VL| Qwen Chat| Grok 3

AI Development Frameworks

n8n| LangChain| Agent SDK| A2A by Google| SmolAgents| LangGraph| CrewAI| Agno| LangFlow| AutoGen| LlamaIndex| Swarm| AutoGPT

Data Science Tools and Techniques

Python| R| SQL| Jupyter Notebooks| TensorFlow| Scikit-learn| PyTorch| Tableau| Apache Spark| Matplotlib| Seaborn| Pandas| Hadoop| Docker| Git| Keras| Apache Kafka| AWS| NLP| Random Forest| Computer Vision| Data Visualization| Data Exploration| Big Data| Common Machine Learning Algorithms| Machine Learning| Google Data Science Agent
👁 Av Logo White

Continue your learning for FREE

Forgot your password?
👁 Av Logo White

Enter OTP sent to

Edit

Wrong OTP.

Enter the OTP

Resend OTP

Resend OTP in 45s

👁 Popup Banner
👁 AI Popup Banner