Python Bitwise Operators

Blog-13.jpg

Bitwise operators in Python allow direct manipulation of data at the binary level. This enables high-performance, low-level control in your code. This operation is essential in domains where memory efficiency, speed, and minute control over the data are very important. In domains like system programming, cryptography, embedded systems, and graphical programming, bitwise operators are widely used.  In this blog, you will explore what bitwise operators in Python are, the different types of bitwise operators in Python, and how each one works with examples in detail.

Table of Contents:

What are Bitwise Operators in Python?

Bitwise operators in Python are symbols that instruct the interpreter of Python to perform operations at a bit level. This is known as binary manipulation. Every integer in Python is stored in Binary format. These bitwise operators are the only ones among the Python operators that let you manipulate individual bits directly. 

Note: Unlike lower-level languages like C or Java, Python supports arbitrary-length integers, so you’re not limited to 8, 16, or 32 bits. You can perform Python bitwise operations on very large numbers without worrying about overflow. This makes bit manipulation in Python highly flexible.

Types of Bitwise Operators in Python

There are six primary Python bitwise operators that allow you to manipulate bits in integers. Each operator performs a different type of bit-level computation, crucial for binary manipulation in Python.

Operator Name Example Description
& Bitwise AND a & b Sets each bit to 1 only if both bits are 1
| Bitwise OR a | b Sets each bit to 1 if at least one bit is 1
^ Bitwise XOR a ^ b Sets each bit to 1 only if the bits are different
~ Bitwise NOT ~a Inverts all bits (1s become 0s and 0s become 1s)
<< Left Shift a << 1 Shifts bits to the left, filling with 0s on the right
>> Right Shift a >> 1 Shifts bits to the right, discarding bits on the right

Bitwise Logical Operators in Python

Bitwise Logical Python Operators compare and manipulate the bits of integers based on Boolean Logic Gates. There are four bitwise logical operators in Python. These are AND, OR, XOR, and NOT. Let us look at each of these one by one, enabling efficient bit manipulation in Python.

Bitwise AND (&) Operator in Python

The bitwise and operator in Python sets each bit to 1 if and only if both corresponding bits are 1. It is represented by &.

Truth Table:

Bit A Bit B A & B
0 0 0
0 1 0
1 0 0
1 1 1

Example:

Python

Output:

Bitwise AND

Explanation: The binary of 10 is 1010, and for 4 is 0100. Applying the AND operation evaluates each bit using the truth table. Ignore the 0x values. Those are hexadecimal notations of the integer.

Bitwise AND

Bitwise OR Operator in Python

The bitwise OR operator in Python is represented by |. This operator sets the bit to one if at least one of the bits is 1. 

Truth Table:

Bit A Bit B A | B
0 0 0
0 1 1
1 0 1
1 1 1

Example:

Python

Output:

Bitwise OR Operator

Explanation: You can see the bit representation of 10 and 4. Based on the OR Truth Table, each bit was evaluated. Ignore the 0x values. Those are hexadecimal notations of the integer.

Bitwise OR Operator

Bitwise XOR (^) Operator in Python

The bitwise XOR operator in Python is denoted by ^. This operator sets the bit to 1 if both of the bits are different, either 0 or 1, it doesn’t matter which. If both bits are the same, it will result in zero.

Truth Table:

Bit A Bit B A ^ B
0 0 0
0 1 1
1 0 1
1 1 0

Python XOR Example:

Python

Output:

Bitwise XOR

Explanation: You can see the binary representation of 10 and 4. Based on the XOR Truth Table, each bit was evaluated. Ignore the 0x values. Those are hexadecimal notations of the integer.

Bitwise XOR

Bitwise NOT(~) Operator in Python

The bitwise NOT operator in Python is represented by ~. It inverts all the bits of a number, turning 0s into 1s and 1s into 0s. This is called taking the 1’s complement of the number.

However, in Python, when you apply ~n, the result is interpreted using two’s complement representation, which is how computers handle negative numbers internally.

In Python, ~n is equivalent to -(n + 1)

Because Python treats the inverted binary as a two’s complement negative integer.

Truth Table:

Bit A ~A
0 1
1 0

Example:

Python

Output:

Bitwise NOT

Explanation: You can see the binary representation of 10. Based on the NOT Truth Table, each bit is inverted.

Bitwise NOT

Why Does ~10 Return -11?

Let us understand it step by step.

a = 10

Binary (8-bit): 00001010

Why 8 bits?

Even though 10 fits in 4 bits (1010), we use 8 bits to better visualise what’s happening; This mimics how computers typically store integers (e.g., a byte = 8 bits), and it helps us interpret the result as a signed binary number. This is essential for binary manipulation in Python.

Apply bitwise NOT (~a) –  this flips every bit

~00001010 -> 11110101

Interpret the result (11110101)

This is the two’s complement representation of a negative number.

To find out which negative number:

  • Invert the bits again: 00001010
  • Add 1: 00001011 → 11
  • So the original result must be -11

Bitwise Shift Operators in Python

The bitwise shift operators in Python shift the bits in the binary representation of a number by a specified number of positions. In Python, we have two bitwise shift operators, Left shift and Right shift.

Left Shift (<<) Bitwise Operator in Python

The left shift operator in Python is represented by a << n. This operator shifts the bits in the binary representation of ‘a‘ to the left by ‘n’ positions. A zero is added to the right, and the leftmost bits are discarded. 

This operation is equivalent to multiplying the number by 2^n.

Example:

Python

Output:

Left Shift

Explanation: Here, in 5 → 0000 0101, all the bits are shifted to the left by 1 in the first example and by 2 in the second example. 

Left Shift

Right Shift (>>) Bitwise Operator in Python

The right shift operator in Python is represented by a >> n. This operator shifts the bits towards the right by n positions. Here, the rightmost bits are discarded, and the leftmost bits are filled based on the sign of the number. 

  • For a Positive Number, 0 is filled on the left.
  • For a Negative Number, 1s are filled on the left to preserve the sign. This is called an arithmetic shift. 
It performs floor division by 2^n.

Example: 

Python

Output: 

Right Shift

Explanation: Here, 5 is represented as 0000 0101, whereas -5 is represented as 1111 1011 (due to 2s Complement). In the first example, 5 is right-shifted by 1, and in the second example, -5 is right-shifted by 1. In the negative number case, 1s were filled in from the left to preserve the sign. 

Right Shift

Difference Between Bitwise and Logical Operators in Python

Aspect Python Bitwise Operators Python Logical Operators
Used For Performing operations on bits of integers Evaluating Boolean expressions
Operands Works on integers Works on boolean values (True or False)
Operators & (AND), | (OR), ^ (XOR), ~ (NOT), <<, >> &&, ||, !
Operation Level Performs operation bit by bit Performs operation on the overall truth value
Return Type Returns an integer result Returns a boolean (True or False)
Example 5 & 3 → 1 (101 & 011 = 001) True and False → False
Common Use Cases Bit masking, low-level hardware operations, and flags Conditional logic, control flow

Bitwise Operators with Negative Numbers in Python

Working with bitwise operators on negative numbers in Python can be complex due to how negative integers are stored in memory.

1. Two’s Complement Representation

  • Python uses two’s complement internally to represent negative numbers.
  • Although Python integers are of unlimited size, bitwise operations mimic fixed-width two’s complement behavior. This is important for binary manipulation in Python for negative values.

2. Bitwise NOT (~)

  • The ~ operator inverts all bits and returns -(n + 1).
  • Example: ~2 gives -3, because all bits are flipped and adjusted in two’s complement form.

3. Bitwise AND, OR, XOR

  • These operators (&, |, ^) work at the bit level.
  • When used with negative numbers, results may be unexpected if you’re not thinking in terms of two’s complement.

4. Shift Operators (<<, >>)

  • Left Shift (<<): Multiplies the number by powers of 2; works the same for positive and negative numbers.
  • Right Shift (>>): It preserves the sign bit in negative numbers (called arithmetic shift), so it fills in 1s from the left.

5. bin() Function and Visualization

  • bin(-5) returns ‘-0b101’, which does not show the two’s complement form.
  • To see the bitwise representation, you need to apply a bitmask like & 0xFF to simulate an 8-bit view.

6. Bit Masking with Negative Numbers

Using a bitmask (e.g., number & 0xFF) can help work with the lower 8 bits and understand how negative numbers behave bitwise.

Bitwise Operator Overloading in Python

The Python bitwise operators can be overloaded. Overloading means you can define custom behavior for bitwise operators when they are used with user-defined objects like classes. This helps in bit manipulation in Python on custom data structures.

Operator overloading allows you to change the way operators behave for your classes by defining special methods, also called magic methods. The Python bitwise operators are overloaded using the following methods:

Operator Method
& __and__
| __or__
^ __xor__
~ __invert__
<< __lshift__
>> __rshift__

Example of Operator Overloading in Python:

Python

Output:

Bitwise Operator Overloading in Python

Explanation: Here, when a & b are called, it triggers the __and__() method, which performs a bitwise AND on the values of a and b, which are 6 and 3, respectively. The result is 2, so the output is Number(2).

Real-World Use Cases of Bitwise Operators in Python

Here are a few real-world use cases of bitwise operators in Python:

  1. Managing Permissions and Flags: Bitwise operators are used to set, check, or remove access permissions like read, write, or execute.
  2. Bit Masking: They are used to isolate or extract specific bits from a binary number.
  3. Swapping Values: Bitwise XOR can be used to swap two numbers without using a temporary variable.
  4. Setting, Clearing, and Toggling Bits: They help in turning specific bits on or off, or flipping their values.
  5. Performance Optimization: Bitwise operations are faster than arithmetic ones and are used in performance-critical applications.
  6. Data Compression and Encryption: Bitwise logic is used in algorithms that compress or encrypt data at the bit level.
  7. Network Protocols and Checksums: These operators are often used in low-level networking tasks like header parsing and error checking.
  8. Graphics Programming: Bitwise operators in Python are also used to manipulate pixel values and colors efficiently by working directly with bits.

Common Pitfalls When Using Bitwise Operators

  1. Getting Confused Between Bitwise and Logical Operators: Using ‘&’ instead of ‘and’, or ‘|’ instead of ‘or’, can lead to unexpected results.
  2. Forgetting Operator Precedence: Bitwise operators have lower precedence than arithmetic but higher than comparison; missing parentheses may cause logic errors.
  3. Misusing Bit Masks: Applying the wrong mask can lead to incorrect bit extraction or setting during bit manipulation in Python.
  4. Using Bitwise Operators on Non-Integers: Bitwise operations only work on integers; thus, using them on floats or strings will cause errors.
  5. Incorrect Shift Operations: Shifting too far left or right can lose data or produce incorrect results.
  6. Ignoring Sign Bits in Negative Numbers: Bitwise operators with negative numbers in Python can behave unexpectedly due to the two’s complement representation.
  7. Making Simple Logic Complex: Using bitwise operations where logical or arithmetic ones are more readable can make code harder to understand.
  8. Not Handling Bit Length Properly: Assuming a fixed number of bits without considering Python’s arbitrary-precision integers can cause bugs.

Conclusion

In this blog, we learned the various bitwise operators available in Python and how they work on a bit level. Python uses 2’s complement representation for negative integers, which explains the behavior of bitwise NOT and right shift operations with negative numbers. You also learned how bitwise shift operators can be used for efficient multiplication and division by powers of 2. You can even overload bitwise operators to define custom behavior for user-defined classes. Bitwise operators are widely used in access control programs. Learning and using them will improve your code. 

To take your skills to the next level, check out this Python training course and gain hands-on experience. Also, prepare for job interviews with Python interview questions prepared by industry experts.

 

Understand Python Basics with a focus on handling files and importing modules

How to Parse a String to a Float or Int in Python – Explore how to parse strings into floats or integers in Python through the examples shared in this post.
Python Arithmetic Operators – You’ll find several examples in this post demonstrating the use of arithmetic operators in Python.
Python Comparison Operators – Python comparison operators are covered in this post with practical examples to illustrate their usage.
Python Assignment Operator – Through this post, you’ll gain insights into how assignment operators work in Python with easy-to-follow examples.
Python Membership and Identity Operators – Membership and identity operators in Python are explained here with simple and effective code samples.
Python Docstrings – Discover how Python docstrings work with helpful examples included in this informative post.
Access Environment Variable Values in Python – This guide shows you how to access environment variable values in Python with practical demonstrations.
Python: How to Get the Last Element of List – Learn how to retrieve the last element of a list in Python using the examples provided in this post.
Access Index Using For Loop in Python – In this post, you’ll see how to use a for loop to access both the index and value in Python with illustrative examples.

Python Bitwise Operators – FAQs

Q1. What are bitwise operators in Python?

Bitwise operators instruct the interpreter to perform operations on the binary representation of integers.

Q2. What is |= in Python?

It is a bitwise assignment OR operator.

Q3. Does Python have XOR?

Yes, Python has an XOR operator denoted by ^.

Q4. What is the '|' symbol in Python?

It is the representation of the Bitwise OR operator.

Q5. What does the |= operator do?

The bitwise assignment OR operator performs bitwise OR on the binary representation of the integers and then assigns the value to the left-hand variable.

Q6. What is the difference between bitwise and logical operators in Python?

Bitwise operators perform operations on individual bits of integers, while logical operators evaluate the overall truth value of boolean expressions.

Q7. Can bitwise operators be overloaded in Python?

Yes, bitwise operators can be overloaded in Python using special methods like __and__, __or__, __xor__, etc.

Q8. What is the use of <<= and >>= in Python?

The <<= and >>= operators in Python perform in-place left and right bitwise shifts, respectively, modifying the original variable.

Q9. Why does ~10 return -11 in Python?

Because ~10 returns -(10 + 1) due to Python using two’s complement representation for bitwise NOT.

Q10. What is the XOR operator in Python and how does it work?

The XOR operator in Python is ^, and it returns 1 for bits that are different and 0 for bits that are the same.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner