Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Bitwise Operators
Next article icon

Python Bitwise Operators

Last Updated : 13 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Python bitwise operators are used to perform bitwise calculations on integers. The integers are first converted into binary and then operations are performed on each bit or corresponding pair of bits, hence the name bitwise operators. The result is then returned in decimal format.

Note: Python bitwise operators work only on integers.

OperatorDescriptionSyntax
&Bitwise ANDx & y
|Bitwise ORx | y
~Bitwise NOT~x
^Bitwise XORx ^ y
>>Bitwise right shiftx>>
<<Bitwise left shiftx<<

Bitwise AND Operator

Python Bitwise AND (&) operator takes two equal-length bit patterns as parameters. The two-bit integers are compared. If the bits in the compared positions of the bit patterns are 1, then the resulting bit is 1. If not, it is 0.

Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise and of both X & y

Note: Here, (111)2 represent binary number.

Python
a = 10 b = 4  # Print bitwise AND operation print("a & b =", a & b) 

Output
a & b = 0 

Bitwise OR Operator

The Python Bitwise OR (|) Operator takes two equivalent length bit designs as boundaries; if the two bits in the looked-at position are 0, the next bit is zero. If not, it is 1.

Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise OR of both X, Y

Python
a = 10 b = 4  # Print bitwise OR operation print("a | b =", a | b) 

Output
a | b = 14 

Bitwise XOR Operator

The Python Bitwise XOR (^) Operator also known as the exclusive OR operator, is used to perform the XOR operation on two operands. XOR stands for "exclusive or", and it returns true if and only if exactly one of the operands is true. In the context of bitwise operations, it compares corresponding bits of two operands. If the bits are different, it returns 1; otherwise, it returns 0.

Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise and of both X & Y

Python
a = 10 b = 4  # print bitwise XOR operation print("a ^ b =", a ^ b) 

Output
a ^ b = 14 

Bitwise NOT Operator

The preceding three bitwise operators are binary operators, necessitating two operands to function. However, unlike the others, this operator operates with only one operand.

Python Bitwise Not (~) Operator works with a single value and returns its one’s complement. This means it toggles all bits in the value, transforming 0 bits to 1 and 1 bits to 0, resulting in the one’s complement of the binary number.

Example: Take two bit values X and Y, where X = 5= (101)2 . Take Bitwise NOT of X.

Python
a = 10 b = 4  # Print bitwise NOT operation print("~a =", ~a) 

Output
~a = -11 

Bitwise Shift

These operators are used to shift the bits of a number left or right thereby multiplying or dividing the number by two respectively. They can be used when we have to multiply or divide a number by two. 

Bitwise Right Shift

Shifts the bits of the number to the right and fills 0 on voids left( fills 1 in the case of a negative number) as a result. Similar effect as of dividing the number with some power of two.

Example 1:
a = 10 = 0000 1010 (Binary)
a >> 1 = 0000 0101 = 5

Example 2:
a = -10 = 1111 0110 (Binary)
a >> 1 = 1111 1011 = -5
Python
a = 10 b = -10  # print bitwise right shift operator print("a >> 1 =", a >> 1) print("b >> 1 =", b >> 1) 

Output
a >> 1 = 5 b >> 1 = -5 

Bitwise Left Shift

Shifts the bits of the number to the left and fills 0 on voids right as a result. Similar effect as of multiplying the number with some power of two.

Example 1:
a = 5 = 0000 0101 (Binary)
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20

Example 2:
b = -10 = 1111 0110 (Binary)
b << 1 = 1110 1100 = -20
b << 2 = 1101 1000 = -40
Python
a = 5 b = -10  # print bitwise left shift operator print("a << 1 =", a << 1) print("b << 1 =", b << 1) 

Output
a << 1 = 10 b << 1 = -20 

Bitwise Operator Overloading

Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because the ‘+’ operator is overloaded by int class and str class. You might have noticed that the same built-in operator or function shows different behavior for objects of different classes, this is called Operator Overloading.

Below is a simple example of Bitwise operator overloading.

Python
# Python program to demonstrate # operator overloading   class Geek():     def __init__(self, value):         self.value = value      def __and__(self, obj):         print("And operator overloaded")         if isinstance(obj, Geek):             return self.value & obj.value         else:             raise ValueError("Must be a object of class Geek")      def __or__(self, obj):         print("Or operator overloaded")         if isinstance(obj, Geek):             return self.value | obj.value         else:             raise ValueError("Must be a object of class Geek")      def __xor__(self, obj):         print("Xor operator overloaded")         if isinstance(obj, Geek):             return self.value ^ obj.value         else:             raise ValueError("Must be a object of class Geek")      def __lshift__(self, obj):         print("lshift operator overloaded")         if isinstance(obj, Geek):             return self.value << obj.value         else:             raise ValueError("Must be a object of class Geek")      def __rshift__(self, obj):         print("rshift operator overloaded")         if isinstance(obj, Geek):             return self.value >> obj.value         else:             raise ValueError("Must be a object of class Geek")      def __invert__(self):         print("Invert operator overloaded")         return ~self.value   # Driver's code if __name__ == "__main__":     a = Geek(10)     b = Geek(12)     print(a & b)     print(a | b)     print(a ^ b)     print(a << b)     print(a >> b)     print(~a) 

Output
And operator overloaded 8 Or operator overloaded 14 Xor operator overloaded 6 lshift operator overloaded 40960 rshift operator overloaded 0 Invert operator overloaded -11 


Note: To know more about operator overloading click here.


Next Article
Python Bitwise Operators

N

nikhilaggarwal3
Improve
Article Tags :
  • Python
  • Python-Operators
Practice Tags :
  • python
  • python-operators

Similar Reads

    Python Operators
    In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. OPERATORS: These are the special symbols. Eg- + , * , /,
    6 min read
    Precedence and Associativity of Operators in Python
    In Python, operators have different levels of precedence, which determine the order in which they are evaluated. When multiple operators are present in an expression, the ones with higher precedence are evaluated first. In the case of operators with the same precedence, their associativity comes int
    4 min read

    Python Arithmetic Operators

    Python Arithmetic Operators
    Python operators are fundamental for performing mathematical calculations. Arithmetic operators are symbols used to perform mathematical operations on numerical values. Arithmetic operators include addition (+), subtraction (-), multiplication (*), division (/), and modulus (%). OperatorDescriptionS
    4 min read
    Difference between / vs. // operator in Python
    In Python, both / and // are used for division, but they behave quite differently. Let's dive into what they do and how they differ with simple examples./ Operator (True Division)The / operator performs true division.It always returns a floating-point number (even if the result is a whole number).It
    2 min read
    Python - Star or Asterisk operator ( * )
    The asterisk (*) operator in Python is a versatile tool used in various contexts. It is commonly used for multiplication, unpacking iterables, defining variable-length arguments in functions, and more.Uses of the asterisk ( * ) operator in PythonMultiplicationIn Multiplication, we multiply two numbe
    3 min read
    What does the Double Star operator mean in Python?
    The ** (double star)operator in Python is used for exponentiation. It raises the number on the left to the power of the number on the right. For example:2 ** 3 returns 8 (since 2³ = 8)It is one of the Arithmetic Operator (Like +, -, *, **, /, //, %) in Python and is also known as Power Operator.Prec
    2 min read
    Division Operators in Python
    Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. There are two types of division operators: Float divisionInteger division( Floor division)When an in
    5 min read
    Modulo operator (%) in Python
    Modulo operator (%) in Python gives the remainder when one number is divided by another. Python allows both integers and floats as operands, unlike some other languages. It follows the Euclidean division rule, meaning the remainder always has the same sign as the divisor. It is used in finding even/
    4 min read

    Python Logical Operators

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences