Python Bitwise Operators

Python Bitwise operations alter binary strings at the bit level. These operations are incredibly basic and are directly supported by the processor. These few operations are necessary in working with device drivers, low-level graphics, cryptography, and network communications. This section provides useful knowledge and examples of Python’s bitwise operators.

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 ‘+’ 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 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
            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
            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
            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
            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
            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)


And operator overloaded
Or operator overloaded
Xor operator overloaded
lshift operator overloaded
rshift operator overloaded
Invert operator overloaded

Python Bitwise Operators: Bitwise NOT

The ~ operator will flip all of the bits in the number. Since computers use signed number representations — most notably, the two’s complement notation to encode negative binary numbers where negative numbers are written with a leading one (1) instead of a leading zero (0).

This means that if you were using 8 bits to represent your two’s-complement numbers, you would treat patterns from 0000 0000 to 0111 1111 to represent numbers from 0 to 127 and reserve 1xxx xxxx to represent negative numbers.

Eight-bit two’s-complement numbers

Bits Unsigned Value Two’s-complement Value

0000 0000 0 0
0000 0001 1 1
0000 0010 2 2
0111 1110 126 126
0111 1111 127 127
1000 0000 128 -128
1000 0001 129 -127
1000 0010 130 -126
1111 1110 254 -2
1111 1111 255 -1

In essence, this means that whereas 1010 0110 has an unsigned value of 166 (arrived at by adding (128 * 1) +

(64 * 0) + (32 * 1) + (16 * 0) + (8 * 0) + (4 * 1) + (2 * 1) + (1 * 0)), it has a two's-complement value of -90 (arrived at by adding (128 * 1) - (64 * 0) - (32 * 1) - (16 * 0) - (8 * 0) - (4 * 1) - (2 * 1) - (1 * 0), and complementing the value).
In this way, negative numbers range down to -128 (1000 0000). Zero (0) is represented as 0000 0000, and minus one (-1) as 1111 1111.

In general, though, this means ~n = -n – 1.

0 = 0b0000 0000 ~0
Out: -1
-1 = 0b1111 1111
1 = 0b0000 0001 ~1
Out: -2
-2 = 1111 1110
2 = 0b0000 0010 ~2
Out: -3
-3 = 0b1111 1101
123 = 0b0111 1011 ~123
Out: -124
-124 = 0b1000 0100

Note, the overall effect of this operation when applied to positive numbers can be summarized:

~n -> -|n+1|

And then, when applied to negative numbers, the corresponding effect is:

~-n -> |n-1|

The following examples illustrate this last rule…

-0 = 0b0000 0000 ~-0
Out: -1
-1 = 0b1111 1111
0 is the obvious exception to this rule, as -0 == 0 always
-1 = 0b1000 0001
Out: 0
0 = 0b0000 0000
-2 = 0b1111 1110 ~-2
Out: 1
1 = 0b0000 0001
-123 = 0b1111 1011 ~-123
Out: 122
122 = 0b0111 1010

Python Bitwise Operators: Bitwise XOR (Exclusive OR)

The ^ operator will perform a binary XOR in which a binary 1 is copied if and only if it is the value of exactly one operand. Another way of stating this is that the result is 1 only if the operands are different. Examples include:

60 = 0b111100
30 = 0b011110
Out: 34
34 = 0b100010
bin(60 ^ 30)

Out: 0b100010

Python Bitwise Operators: Bitwise AND

The & operator will perform a binary AND, where a bit is copied if it exists in both operands. That means:

60 = 0b111100
30 = 0b011110
Out: 28
28 = 0b11100
bin(60 & 30)

Out: 0b11100

Python Bitwise Operators: Bitwise OR

The | operator will perform a binary “or,” where a bit is copied if it exists in either operand. That means:

60 = 0b111100
30 = 0b011110
Out: 62
62 = 0b111110
bin(60 | 30)

Out: 0b111110

Python Bitwise Operators: Bitwise Left Shift

The << operator will perform a bitwise “left shift,” where the left operand’s value is moved left by the number of bits given by the right operand in python.

# 2 = 0b10          
2 << 2
# Out: 8
# 8 = 0b1000
bin(2 << 2)
# Out: 0b1000
Performing a left bit shift of is equivalent to multiplication by : 1 2
# Out: 14
Performing a left bit shift of is equivalent to multiplication by : n 2**n

Out: 48

Python Bitwise Operators: Bitwise Right Shift

The >> operator will perform a bitwise “right shift,” where the left operand’s value is moved right by the number of bits given by the right operand.

8 = 0b1000
Out: 2
2 = 0b10
bin(8 >> 2)

Out: 0b10

Performing a right bit shift of 1 is equivalent to integer division by 2:


Out: 18


Out: 7

Performing a right bit shift of n is equivalent to integer division by 2**n:


Out: 3


Out: 7

Inplace Operations

All of the Bitwise operators (except ~) have their own in place versions

a = 0b001
a &= 0b010

a = 0b000

a = 0b001
a |= 0b010

a = 0b011

a = 0b001
a <<= 2

a = 0b100

a = 0b100
a >>= 2

a = 0b001

a = 0b101
a ^= 0b011

a = 0b110

Learn More Here

Must Read Python Interview Questions

200+ Python Tutorials With Coding Examples

Python Language Basics TutorialPython String Representations of Class Instances
Python For Beginners TutorialPython Debugging Tutorial
Python Data Types TutorialReading and Writing CSV File Using Python
Python Indentation TutorialWriting to CSV in Python from String/List
Python Comments and Documentation TutorialPython Dynamic Code Execution Tutorial
Python Date And Time TutorialPython Code Distributing using Pyinstaller
Python Date Formatting TutorialPython Data Visualization Tutorial
Python Enum TutorialPython Interpreter Tutorial
Python Set TutorialPython Args and Kwargs
Python Mathematical Operators TutorialPython Garbage Collection Tutorial
Python Bitwise Operators TutorialPython Pickle Data Serialisation
Python Bolean Operators TutorialPython Binary Data Tutorial
Python Operator Precedance TutorialPython Idioms Tutorial
Python Variable Scope And Binding TutorialPython Data Serialization Tutorial
Python Conditionals TutorialPython Multiprocessing Tutorial
Python Comparisons TutorialPython Multithreading Tutorial
Python Loops TutorialPython Processes and Threads
Python Arrays TutorialPython Concurrency Tutorial
Python Multidimensional Arrays TutorialPython Parallel Computation Tutorial
Python List TutorialPython Sockets Module Tutorial
Python List Comprehensions TutorialPython Websockets Tutorial
Python List Slicing TutorialSockets Encryption Decryption in Python
Python Grouby() TutorialPython Networking Tutorial
Python Linked Lists TutorialPython http Server Tutorial
Linked List Node TutorialPython Flask Tutorial
Python Filter TutorialIntroduction to Rabbitmq using Amqpstorm Python
Python Heapq TutorialPython Descriptor Tutorial
Python Tuple TutorialPython Tempflile Tutorial
Python Basic Input And Output TutorialInput Subset and Output External Data Files using Pandas in Python
Python Files And Folders I/O TutorialUnzipping Files in Python Tutorial
Python os.path TutorialWorking with Zip Archives in Python
Python Iterables And Iterators Tutorialgzip in Python Tutorial
Python Functions TutorialStack in Python Tutorial
Defining Functions With List Arguments In PythonWorking with Global Interpreter Lock (GIL)
Functional Programming In PythonPython Deployment Tutorial
Partial Functions In PythonPython Logging Tutorial
Decorators Function In PythonPython Server Sent Events Tutorial
Python Classes TutorialPython Web Server Gateway Interface (WSGI)
Python Metaclasses TutorialPython Alternatives to Switch Statement
Python String Formatting TutorialPython Packing and Unpacking Tutorial
Python String Methods TutorialAccessing Python Sourcecode and Bytecode
Using Loops Within Functions In PythonPython Mixins Tutorial
Python Importing Modules TutorialPython Attribute Access Tutorial
Difference Betweeb Module And Package In PythonPython Arcpy Tutorial
Python Math Module TutorialPython Abstract Base Class Tutorial
Python Complex Math TutorialPython Plugin and Extension Classes
Python Collections Module TutorialPython Immutable Datatypes Tutorial
Python Operator Module TutorialPython Incompatibilities Moving from Python 2 to Python 3
Python JSON Module TutorialPython 2to3 Tool Tutorial
Python Sqlite3 Module TutorialNon-Official Python implementations
Python os Module TutorialPython Abstract Syntax Tree
Python Locale Module TutorialPython Unicode and Bytes
Python Itertools Module TutorialPython Serial Communication (pyserial)
Python Asyncio Module TutorialNeo4j and Cypher using Py2Neo
Python Random Module TutorialBasic Curses with Python
Python Functools Module TutorialTemplates in Python
Python dis Module TutorialPython Pillow
Python Base64 Module TutorialPython CLI subcommands with precise help output
Python Queue Module TutorialPython Database Access
Python Deque Module TutorialConnecting Python to SQL Server
Python Webbrowser Module TutorialPython and Excel
Python tkinter TutorialPython Turtle Graphics
Python pyautogui Module TutorialPython Persistence
Python Indexing And Slicing TutorialPython Design Patterns
Python Plotting With Matplotlib TutorialPython hashlib
Python Graph Tool TutorialCreating a Windows Service Using Python
Python Generators TutorialMutable vs Immutable (and Hashable) in Python
Python Reduce TutorialPython configparser
Python Map Function TutorialPython Optical Character Recognition
Python Exponentiation TutorialPython Virtual Environments
Python Searching TutorialPython Virtual Environment – virtualenv
Sorting Minimum And Maximum In PythonPython Virtual environment with virtualenvwrapper
Python Print Function TutorialCreate virtual environment with virtualenvwrapper in windows
Python Regular Expressions Regex TutorialPython sys Tutorial
Copying Data In Python TutorialChemPy – Python package
Python Context Managers (“with” Statement) TutorialPython pygame
Python Name Special Variable TutorialPython pyglet
Checking Path Existence And Permissions In PythonWorking with Audio in Python
Creating Python Packages TutorialPython pyaudio
Usage of pip Module In Python TutorialPython shelve
Python PyPi Package Manager TutorialIoT Programming with Python and Raspberry PI
Parsing Command Line Arguments In Pythonkivy – Cross-platform Python Framework for NUI Development
Python Subprocess Library TutorialPandas Transform
Python TutorialPython vs. JavaScript
Python Recursion TutorialCall Python from C#
Python Type Hints TutorialPython Writing Extensions
Python Exceptions TutorialPython Lex-Yacc
Raise Custom Exceptions In PythonPython Unit Testing
Python Commonwealth Exceptions TutorialPython py.test
Python urllib TutorialPython Profiling
Web Scraping With Python TutorialPython Speed of Program
Python HTML Parsing TutorialPython Performance Optimization
Manipulating XML In PythonPython Security and Cryptography
Python Requests Post TutorialSecure Shell Connection in Python
Python Distribution TutorialPython Anti Patterns
Python Property Objects TutorialPython Common Pitfalls
Python Overloading TutorialPython Hidden Features
Python Polymorphism TutorialPython For Machine Learning
Python Method Overriding TutorialPython Interview Questions And Answers For Experienced
Python User Defined Methods TutorialPython Coding Interview Questions And Answers
Python Programming Tutorials With Examples

Other Python Tutorials

Leave a Comment