Tutorial

Python Bitwise Operators

Published on August 3, 2022
author

Pankaj

Python Bitwise Operators

Python bitwise operators are used to perform bitwise calculations on integers. The integers are converted into binary format and then operations are performed bit by bit, hence the name bitwise operators. Python bitwise operators work on integers only and the final output is returned in the decimal format. Python bitwise operators are also called binary operators.

Python Bitwise Operators

There are 6 bitwise operators in Python. The below table provides short details about them.

Bitwise Operator Description Simple Example
& Bitwise AND Operator 10 & 7 = 2
Bitwise OR Operator
^ Bitwise XOR Operator 10 ^ 7 = 13
~ Bitwise Ones’ Compliment Operator ~10 = -11
<< Bitwise Left Shift operator 10<<2 = 40
>> Bitwise Right Shift Operator 10>>1 = 5

Let’s look into these operators one by one and understand how they work.

1. Bitwise AND Operator

Python bitwise and operator returns 1 if both the bits are 1, otherwise 0.

>>> 10&7
2
>>> 
Python Bitwise And Operator
Python Bitwise And Operator

2. Bitwise OR Operator

Python bitwise or operator returns 1 if any of the bits is 1. If both the bits are 0, then it returns 0.

>>> 10|7
15
>>> 
Python Bitwise Or Operator
Python Bitwise Or Operator

3. Bitwise XOR Operator

Python bitwise XOR operator returns 1 if one of the bits is 0 and the other bit is 1. If both the bits are 0 or 1, then it returns 0.

>>> 10^7
13
>>> 
Python Bitwise Xor Operator
Python Bitwise XOR Operator

4. Bitwise Ones’ Complement Operator

Python Ones’ complement of a number ‘A’ is equal to -(A+1).

>>> ~10
-11
>>> ~-10
9
>>> 
Python Bitwise Ones Complement Operator
Python Bitwise Ones Complement Operator

5. Bitwise Left Shift Operator

Python bitwise left shift operator shifts the left operand bits towards the left side for the given number of times in the right operand. In simple terms, the binary number is appended with 0s at the end.

>>> 10 << 2
40
>>> 
Python Bitwise Left Shift Operator
Python Bitwise Left Shift Operator

6. Bitwise Right Shift Operator

Python right shift operator is exactly the opposite of the left shift operator. Then left side operand bits are moved towards the right side for the given number of times. In simple terms, the right side bits are removed.

>>> 10 >> 2
2
>>>  
Python Bitwise Right Shift Operator
Python Bitwise Right Shift Operator

Python Bitwise Operator Overloading

Python supports operator overloading. There are various methods that we can implement to support bitwise operators for our custom objects.

Bitwise Operator Method to Implement
& __and__(self, other)
^ __xor__(self, other)
~ __invert__(self)
<< __lshift__(self, other)
>> __rshift__(self, other)

Here is an example of a bitwise operator overloading for our custom object.

class Data:
    id = 0

    def __init__(self, i):
        self.id = i

    def __and__(self, other):
        print('Bitwise AND operator overloaded')
        if isinstance(other, Data):
            return Data(self.id & other.id)
        else:
            raise ValueError('Argument must be object of Data')

    def __or__(self, other):
        print('Bitwise OR operator overloaded')
        if isinstance(other, Data):
            return Data(self.id | other.id)
        else:
            raise ValueError('Argument must be object of Data')

    def __xor__(self, other):
        print('Bitwise XOR operator overloaded')
        if isinstance(other, Data):
            return Data(self.id ^ other.id)
        else:
            raise ValueError('Argument must be object of Data')

    def __lshift__(self, other):
        print('Bitwise Left Shift operator overloaded')
        if isinstance(other, int):
            return Data(self.id << other)
        else:
            raise ValueError('Argument must be integer')

    def __rshift__(self, other):
        print('Bitwise Right Shift operator overloaded')
        if isinstance(other, int):
            return Data(self.id >> other)
        else:
            raise ValueError('Argument must be integer')

    def __invert__(self):
        print('Bitwise Ones Complement operator overloaded')
        return Data(~self.id)

    def __str__(self):
        return f'Data[{self.id}]'


d1 = Data(10)
d2 = Data(7)

print(f'd1&d2 = {d1&d2}')
print(f'd1|d2 = {d1|d2}')
print(f'd1^d2 = {d1^d2}')
print(f'd1<<2 = {d1<<2}')
print(f'd1>>2 = {d1>>2}')
print(f'~d1 = {~d1}')

Output:

Bitwise AND operator overloaded
d1&d2 = Data[2]
Bitwise OR operator overloaded
d1|d2 = Data[15]
Bitwise XOR operator overloaded
d1^d2 = Data[13]
Bitwise Left Shift operator overloaded
d1<<2 = Data[40]
Bitwise Right Shift operator overloaded
d1>>2 = Data[2]
Bitwise Ones Complement operator overloaded
~d1 = Data[-11]

If you are not familiar with the new string formatting, please read f-strings in Python.

Summary

Python bitwise operators are mostly used in mathematical calculations. We can implement specific methods to support bitwise operators for our custom class implementations too.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pankaj

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
January 25, 2022

Awesome! I loved the explanation!

- Radhika

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    October 19, 2020

    Great Description.Appreciate the efforts.

    - Pranav Sudhir

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      October 13, 2020

      made my concepts clear thank you!!!

      - Parth Jain

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        July 16, 2020

        a = 81 a << 2 = 324 Can you please explain this ?

        - Rekha

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          January 3, 2020

          very nice and clear, thank you !

          - h.agnes

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            December 8, 2019

            How bitwise NOT works…?

            - UDHAYAKUMAR

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              November 14, 2019

              In the 5 section : “Bitwise Left Shift Operator” >>> 10 >> 2 40 >>> should be replaced by >>> 10 << 2 40 >>>

              - Nathanael HANIA

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                November 12, 2019

                Very succinct and clear description, awesome job!

                - magicandcode

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  November 1, 2019

                  i understand very clearly

                  - pavani

                    Try DigitalOcean for free

                    Click below to sign up and get $200 of credit to try our products over 60 days!

                    Sign up

                    Join the Tech Talk
                    Success! Thank you! Please check your email for further details.

                    Please complete your information!

                    Become a contributor for community

                    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                    DigitalOcean Documentation

                    Full documentation for every DigitalOcean product.

                    Resources for startups and SMBs

                    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                    Get our newsletter

                    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                    New accounts only. By submitting your email you agree to our Privacy Policy

                    The developer cloud

                    Scale up as you grow — whether you're running one virtual machine or ten thousand.

                    Get started for free

                    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                    *This promotional offer applies to new accounts only.