For working professionals
For fresh graduates
More
Python Tutorials - Elevate You…
1. Introduction to Python
2. Features of Python
3. How to install python in windows
4. How to Install Python on macOS
5. Install Python on Linux
6. Hello World Program in Python
7. Python Variables
8. Global Variable in Python
9. Python Keywords and Identifiers
10. Assert Keyword in Python
11. Comments in Python
12. Escape Sequence in Python
13. Print In Python
14. Python-if-else-statement
15. Python for Loop
16. Nested for loop in Python
17. While Loop in Python
18. Python’s do-while Loop
19. Break in Python
20. Break Pass and Continue Statement in Python
21. Python Try Except
22. Data Types in Python
23. Float in Python
24. String Methods Python
25. List in Python
26. List Methods in Python
27. Tuples in Python
28. Dictionary in Python
29. Set in Python
30. Operators in Python
31. Boolean Operators in Python
32. Arithmetic Operators in Python
33. Assignment Operator in Python
34. Bitwise operators in Python
Now Reading
35. Identity Operator in Python
36. Operator Precedence in Python
37. Functions in Python
38. Lambda and Anonymous Function in Python
39. Range Function in Python
40. len() Function in Python
41. How to Use Lambda Functions in Python?
42. Random Function in Python
43. Python __init__() Function
44. String Split function in Python
45. Round function in Python
46. Find Function in Python
47. How to Call a Function in Python?
48. Python Functions Scope
49. Method Overloading in Python
50. Method Overriding in Python
51. Static Method in Python
52. Python List Index Method
53. Python Modules
54. Math Module in Python
55. Module and Package in Python
56. OS module in Python
57. Python Packages
58. OOPs Concepts in Python
59. Class in Python
60. Abstract Class in Python
61. Object in Python
62. Constructor in Python
63. Inheritance in Python
64. Multiple Inheritance in Python
65. Encapsulation in Python
66. Data Abstraction in Python
67. Opening and closing files in Python
68. How to open JSON file in Python
69. Read CSV Files in Python
70. How to Read a File in Python
71. How to Open a File in Python?
72. Python Write to File
73. JSON Python
74. Python JSON – How to Convert a String to JSON
75. Python JSON Encoding and Decoding
76. Exception Handling in Python
77. Recursion in Python
78. Python Decorators
79. Python Threading
80. Multithreading in Python
81. Multiprocеssing in Python
82. Python Regular Expressions
83. Enumerate() in Python
84. Map in Python
85. Filter in Python
86. Eval in Python
87. Difference Between List, Tuple, Set, and Dictionary in Python
88. List to String in Python
89. Linked List in Python
90. Length of list in Python
91. Python List remove() Method
92. How to Add Elements in a List in Python
93. How to Reverse a List in Python?
94. Difference Between List and Tuple in Python
95. List Slicing in Python
96. Sort in Python
97. Merge Sort in Python
98. Selection Sort in Python
99. Sort Array in Python
100. Sort Dictionary by Value in Python
101. Datetime Python
102. Random Number in Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
106. Anagram Program in Python
107. Append in Python
108. Applications of Python
109. Armstrong Number in Python
110. Assert in Python
111. Binary Search in Python
112. Binary to Decimal in Python
113. Bool in Python
114. Calculator Program in Python
115. chr in Python
116. Control Flow Statements in Python
117. Convert String to Datetime Python
118. Count in python
119. Counter in Python
120. Data Visualization in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
124. Fibonacci Series in Python
125. Format in Python
126. GCD of Two Numbers in Python
127. How to Become a Python Developer
128. How to Run Python Program
129. In Which Year Was the Python Language Developed?
130. Indentation in Python
131. Index in Python
132. Interface in Python
133. Is Python Case Sensitive?
134. Isalpha in Python
135. Isinstance() in Python
136. Iterator in Python
137. Join in Python
138. Leap Year Program in Python
139. Lexicographical Order in Python
140. Literals in Python
141. Matplotlib
142. Matrix Multiplication in Python
143. Memory Management in Python
144. Modulus in Python
145. Mutable and Immutable in Python
146. Namespace and Scope in Python
147. OpenCV Python
148. Operator Overloading in Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
152. Pattern Program in Python
153. Perfect Number in Python
154. Permutation and Combination in Python
155. Prime Number Program in Python
156. Python Arrays
157. Python Automation Projects Ideas
158. Python Frameworks
159. Python Graphical User Interface GUI
160. Python IDE
161. Python input and output
162. Python Installation on Windows
163. Python Object-Oriented Programming
164. Python PIP
165. Python Seaborn
166. Python Slicing
167. type() function in Python
168. Queue in Python
169. Replace in Python
170. Reverse a Number in Python
171. Reverse a string in Python
172. Reverse String in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
178. Speech Recognition in Python
179. Split in Python
180. Square Root in Python
181. String Comparison in Python
182. String Formatting in Python
183. String Slicing in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
187. Sum of Digits of a Number in Python
188. Sum of n Natural Numbers in Python
189. Sum of Prime Numbers in Python
190. Switch Case in Python
191. Python Program to Transpose a Matrix
192. Type Casting in Python
193. What are Lists in Python?
194. Ways to Define a Block of Code
195. What is Pygame
196. Why Python is Interpreted Language?
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.