For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
Bitwise operators in Python manipulate individual bits of data. These operations are useful for low-level tasks like setting or clearing specific bits.
Many developers don’t use bitwise operators in Python, limiting their code optimization. Understanding these operators can make your code more efficient, especially for performance-critical applications.
In this article, we’ll explore bitwise operators in Python with examples, including the bitwise not operator in Python and how it works.
By the end, you will have a solid understanding of bitwise operations and how to use them effectively in your Python code.
“Enhance your Python skills further with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey!”
Bitwise operators in Python manipulate individual bits of integers. They are useful for low-level operations and optimizing code for tasks like network programming or encryption.
Here’s an overview of Bitwise Operators
Operator | Symbol | Example (Output) |
AND | & | 4 & 5 = 4 |
OR | | | 4 | 5 = 5 |
XOR | ^ | 4 ^ 5 = 1 |
NOT | ~ | ~4 = -5 |
The AND operator compares each corresponding bit of two numbers. It returns 1 if both bits are 1; otherwise, it returns 0.
Example:
4 & 5
Output:
4
Explanation:
Let’s look at another example:
Suppose you're working on a system where you need to quickly check if a number is even or odd.
In binary, even numbers have a 0 in the least significant bit (rightmost), while odd numbers have a 1 in that bit.
# check if the number is odd or even
number = 7
# use bitwise AND with 1 to check the least significant bit
if number & 1:
print("Odd")
else:
print("Even")
Output:
Odd
Explanation:
This approach is faster than using modulus (%) for checking even or odd. The bitwise AND operator checks only the last bit, making it a compact and quick operation.
The OR operator compares each corresponding bit of two numbers. It returns 1 if at least one bit is 1; otherwise, it returns 0.
Example:
4 | 5
Output:
5
Explanation:
Let’s look at another example:
Imagine you're building a system where users can have multiple permissions (read, write, execute), represented as individual bits.
You can use the bitwise OR operator to combine multiple permissions and grant a user more than one permission at once.
# define permissions (each permission is a separate bit)
READ = 0b001 #read permission
WRITE = 0b010 #write permission
EXECUTE = 0b100 #execute permission
# current user permissions (no permissions granted yet)
user_permissions = 0b000
# grant Read and Execute permissions to the user
new_permissions = user_permissions | READ | EXECUTE
# display new permissions in binary
print(bin(new_permissions))
Output:
0b101
Explanation:
Why Use Bitwise OR Here?
The OR operator lets you easily combine multiple permissions without affecting others. It allows you to handle permissions efficiently using a single integer.
The XOR operator compares the corresponding bits of two numbers and returns 1 if the bits are different; otherwise returns 0.
Example:
4 ^ 5
Output:
1
Explanation:
Let’s look at another example:
The XOR (exclusive OR) operator is commonly used to toggle specific bits in a number. When you perform XOR between two bits, it returns 1 if the bits are different and 0 if they are the same.
# initial value in binary
number = 0b101010 # binary: 42
# mask to toggle the 3rd bit (from the right)
mask_toggle = 0b00100 # mask for toggling the 3rd bit
# toggle the 3rd bit using XOR
number_toggled = number ^ mask_toggle
print(bin(number_toggled)) #output: 0b101110 (46)
# toggle the 3rd bit again (to revert back)
number_reverted = number_toggled ^ mask_toggle
print(bin(number_reverted)) # output: 0b101010 (42)
Output:
0b101110 0b101010
Explanation:
Why Use XOR Here?
The NOT operator inverts the bits of a number, changing 1 to 0 and 0 to 1. This is also known as bitwise negation.
Example:
~4
Output:
-5
Explanation:
Let’s look at another example:
Let’s say you're building a system that needs to quickly invert the sign of an integer, effectively converting a positive number to a negative one or vice versa.
# positive number
number = 10 # binary: 1010
# apply the bitwise NOT operator to invert the sign
inverted_number = ~number
print(inverted_number) # output: -11
# apply bitwise NOT again to revert back to original number
original_number = ~inverted_number
print(original_number) # output: 10
Output:
-11 # After applying bitwise NOT (negative version of the number)10 # After applying bitwise NOT again (back to original positive number)
Explanation:
Why Use Bitwise NOT Here?
“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”
Bitwise shift operators in Python allow you to shift the bits of a number left or right. These operators are commonly used to manipulate data efficiently at the bit level.
Operator | Symbol | Example (Output) |
Left Shift | << | 4 << 1 = 8 |
Right Shift | >> | 4 >> 1 = 2 |
The Left Shift operator (<<) shifts the bits of a number to the left by a specified number of positions. Each left shift effectively multiplies the number by 2.
Example:
# number to shift
number = 4 #binary: 0100
# left shift by 1 position
result = number << 1
print(result) #output: 8
Output:
8
Explanation:
The Right Shift operator (>>) shifts the bits of a number to the right by a specified number of positions. Each right shift effectively divides the number by 2.
Example:
#number to shift
number = 4 #binary: 0100
#right shift by 1 position
result = number >> 1
print(result) #output: 2
Output:
2
Explanation:
Bitwise operator overloading in Python allows you to define how bitwise operators like &, |, ^, <<, and >> behave when applied to objects of custom classes.
This allows you to extend the behavior of these operators beyond their default functionality for your own objects in Python, making it possible to integrate bitwise logic into custom data structures.
Let’s look at an example:
Suppose you’re designing a class in Python to represent a BitVector (a sequence of bits). You want to perform bitwise operations on instances of this class.
class BitVector:
def __init__(self, value):
self.value = value
# Overloading the AND (&) operator
def __and__(self, other):
return BitVector(self.value & other.value)
# Overloading the OR (|) operator
def __or__(self, other):
return BitVector(self.value | other.value)
# Overloading the XOR (^) operator
def __xor__(self, other):
return BitVector(self.value ^ other.value)
# Overloading the Left Shift (<<) operator
def __lshift__(self, n):
return BitVector(self.value << n)
# Overloading the Right Shift (>>) operator
def __rshift__(self, n):
return BitVector(self.value >> n)
def __repr__(self):
return f'BitVector({bin(self.value)})'
# Create two BitVector instances
bv1 = BitVector(0b1101) # Binary: 1101 (13 in decimal)
bv2 = BitVector(0b1011) # Binary: 1011 (11 in decimal)
# Perform bitwise operations
result_and = bv1 & bv2
result_or = bv1 | bv2
result_xor = bv1 ^ bv2
result_lshift = bv1 << 2
result_rshift = bv2 >> 1
# Print results
print(result_and)
print(result_or)
print(result_xor) )
print(result_lshift)
print(result_rshift)
Output:
BitVector(0b1001)BitVector(0b1111)BitVector(0b110)BitVector(0b110100)BitVector(0b101)
Explanation:
Why Use Bitwise Operator Overloading?
Pros and Cons
Pros:
Cons:
Let’s explore a few real-world uses where bitwise operators in Python with examples come into play.
1. Optimizing Performance
Bitwise operators can replace traditional arithmetic operations like multiplication or division by powers of two, making code faster and more efficient.
For example, instead of multiplying by 2, you can use left shift (<<) or divide by 2 using right shift (>>).
2. Network Programming
Bitwise operations are widely used in network programming to manage IP addresses and subnet masks.
For instance, AND (&) is used to check if an IP address belongs to a certain subnet. Similarly, OR (|) is used to combine subnet masks, and XOR (^) can be used to generate checksums or error detection codes.
Also Read: Computer Networking Basics: Network Types, Technologies, Topologies, Pros and Cons
3. Cryptography
Bitwise operators are fundamental in cryptography, especially in encryption and decryption algorithms.
The XOR operator is commonly used for simple encryption, where the same key is used to encrypt and decrypt data. Multiple bitwise operators like AND, OR, and XOR are often combined to create secure encryption schemes, such as the AES algorithm.
4. Flag Manipulation
Bitwise operators allow for efficient management of flags or settings in a single integer.
For example, bitwise OR (|) can be used to set a flag, bitwise AND (&) can clear a flag, and XOR (^) can toggle a flag. This is useful in system settings, role-based access control systems, or any application that requires managing multiple binary flags efficiently.
5. Image Processing
In image processing, bitwise operators are used to manipulate pixel data.
For example, AND can be used to mask specific regions of an image, while OR can be used to combine multiple images. XOR is used in various image manipulation algorithms to blend or extract information from multiple images.
Bitwise operations are often used to process images at the pixel level, which is important in fields like computer vision or graphics.
Also Read: Feature Extraction in Image Processing: Image Feature Extraction in ML
6. Compression Algorithms
Bitwise operations are widely used in data compression algorithms, such as Run-Length Encoding (RLE) and Huffman coding, where bitwise operators manipulate the bits to represent data efficiently. By using bitwise operators, you can reduce the amount of data stored or transmitted, which is critical in areas like file compression or network transmission.
7. Error Detection and Correction
In systems like cyclic redundancy checks (CRC), bitwise operations like XOR and AND are used to detect and correct errors in transmitted data.
For instance, XOR is used to generate checksums, and these can then be checked at the receiving end to verify data integrity.
8. Game Development
In game development, bitwise operators are used to manage multiple game states or properties efficiently.
For example, bitwise OR is used to enable features such as player abilities, while bitwise AND can be used to check which abilities are enabled. This allows developers to store and check multiple flags in a single integer, reducing memory usage.
By understanding and applying bitwise operators in Python with examples, you’ll be able to tackle problems that involve low-level data manipulation, optimize your code, and create more efficient systems.
Bitwise operators in Python with examples are operators that perform bit-level operations on integers. They manipulate individual bits of numbers, providing efficient solutions for tasks like setting flags, encryption, and performance optimization.
The bitwise NOT operator in Python (~) inverts the bits of a number, turning all 1s into 0s and vice versa. It is typically used for bitwise negation or two's complement calculations.
Yes! Bitwise AND (&) compares two numbers bit by bit. If both bits are 1, the result is 1; otherwise, it's 0. For example: 5 & 3 results in 1 because 101 & 011 = 001.
Use bitwise OR (|) when you need to combine bits. It sets the corresponding result bit to 1 if any of the bits being compared is 1. For example, 5 | 3 results in 7.
Bitwise operators in Python with examples allow for faster operations than traditional arithmetic, especially when dealing with low-level tasks like shifting bits, setting flags, or handling binary data.
The bitwise NOT operator in Python affects signed numbers by converting them to their negative counterparts using two's complement representation. For instance, ~5 results in -6.
Bitwise AND (&) only sets the result bit to 1 when both bits are 1, whereas bitwise OR (|) sets the result bit to 1 if at least one of the bits is 1.
The bitwise shift operators (<< for left shift, >> for right shift) shift bits to the left or right by a specified number of positions. They are commonly used for multiplying or dividing numbers by powers of two.
The bitwise NOT operator in Python is useful for inverting the binary representation of numbers, which is crucial in systems programming, encryption, and working with negative numbers in two's complement.
No, bitwise operators in Python with examples only work on integer data types. If you need to manipulate non-integer types, consider converting them to integers first.
Bitwise operators in Python with examples are widely used for performance optimization, flag manipulation, networking (e.g., IP address checking), cryptography, and low-level system tasks such as error detection and correction.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.