Back to Python
2026-02-036 min read

Python Bitwise NOT Operator (~)

Learn Python Bitwise NOT Operator (~) step by step with clear examples and exercises.

Title: Python Bitwise NOT Operator (~)

Why This Matters

Understanding the bitwise NOT operator is crucial for any Python programmer who wants to optimize code performance, debug complex issues, and solve challenging problems. The ~ operator, also known as the bitwise NOT operator, is an essential tool that every Python developer should master. This lesson will delve into the practical uses of the bitwise NOT operator in Python, providing you with a comprehensive understanding of its workings, common pitfalls to avoid, and best practices for using it effectively.

Prerequisites

Before diving into the bitwise NOT operator, it's essential to have a solid grasp of the following topics:

  • Basic Python syntax, including variables, data types, and operators
  • Understanding of numbers and their binary representation
  • Familiarity with other bitwise operators such as AND (&), OR (|), XOR (^), and shift operators (<< and >>)
  • Basic understanding of signed and unsigned integers, including how Python handles negative numbers internally
  • Knowledge of Python's built-in functions like abs(), ceil(), and floor() to handle large numbers more gracefully

Core Concept

The bitwise NOT operator, denoted by the ~ symbol in Python, performs a bit-by-bit complement operation on its operand. In other words, it flips each bit of the given number from 0 to 1 (and vice versa). For example, if we apply the bitwise NOT operator on the binary representation of the decimal number 7 (which is 0b111), the result will be the binary representation of the decimal number 8 (which is 0b1000):

Original number in binary and decimal

num = 7

binary_num = bin(num)[2:]

print("Original Number:", binary_num, "Decimal:", num)

Applying bitwise NOT operator

bitwise_not_num = ~num

inverted_binary_num = bin(bitwise_not_num)[2:]

print("Inverted Number:", inverted_binary_num, "Decimal:", bitwise_not_num)


Output:

Original Number: 111 Decimal: 7

Inverted Number: 000 Decimal: 8


### Bitwise NOT with Negative Numbers

When working with negative numbers, it's important to understand that the bitwise NOT operator will produce a result with the most significant bit (MSB) set to 1 instead of 0. This can lead to confusion when working with signed integers. For example:

num = -5

binary_num = bin(num)[2:]

print("Original Number:", binary_num, "Decimal:", num)

bitwise_not_num = ~num

inverted_binary_num = bin(bitwise_not_num)[2:]

print("Inverted Number:", inverted_binary_num, "Decimal:", bitwise_not_num)


Output:

Original Number: 101 Decimal: -5

Inverted Number: 1101 Decimal: 9


### Bitwise NOT with Large Numbers

Python's built-in integer type, `int`, has a limited range (approximately -9e18 to 9e18). If you perform bitwise operations on numbers outside this range, you may encounter unexpected results due to overflow or underflow errors. To avoid such issues, consider using the `sys` module's `setrecursionlimit()` function to increase the maximum recursion depth and the `math` module's `ceil()` and `floor()` functions to handle large numbers more gracefully.

Worked Example

Let's consider a practical example where we use the bitwise NOT operator to implement a simple function that swaps two numbers without using a temporary variable.

def swap_without_temp(a, b):

XORing a and b

xor = a ^ b

XORing a with b's complement (~b)

a = a ^ ~b

XORing b with a's complement (~a)

b = b ^ ~a

return a, b


Now let's test our function:

num1 = 5

num2 = 7

print("Before swapping:", num1, ",", num2)

num1, num2 = swap_without_temp(num1, num2)

print("After swapping:", num1, ",", num2)


Output:

Before swapping: 5 , 7

After swapping: 7 , 5


### Worked Example - Alternative Swap Function

Here's an alternative implementation of the swap function using only bitwise operators, without relying on the XOR operation:

def swap_without_temp(a, b):

a = a | (b << 32)

b = b | (a >> 32)

a = a & ~(b << 32)

b = b & ~(a >> 32)

return a, b

Common Mistakes

  1. Misunderstanding the bitwise NOT operator's behavior with negative numbers

The bitwise NOT operator applied to a negative number will produce a positive number, but the resulting binary representation will have the most significant bit (MSB) set to 1 instead of 0. This can lead to confusion when working with signed integers.

  1. Neglecting to handle overflow or underflow errors when performing bitwise operations on large numbers

Python's built-in integer type, int, has a limited range (approximately -9e18 to 9e18). If you perform bitwise operations on numbers outside this range, you may encounter unexpected results due to overflow or underflow errors. To avoid such issues, consider using the sys module's setrecursionlimit() function to increase the maximum recursion depth and the math module's ceil() and floor() functions to handle large numbers more gracefully.

  1. Assuming that the bitwise NOT operator works identically on all data types

The bitwise NOT operator can only be applied to integers (both positive and negative). Attempting to use it with other data types, such as floating-point numbers or strings, will result in a TypeError.

  1. Incorrectly applying the bitwise NOT operator when working with signed integers

When working with signed integers, it's essential to understand that the bitwise NOT operator changes the sign of the number and flips the bits. For example:

num = -5
bitwise_not_num = ~num
print("Original Number:", num)
print("Inverted Number:", bitwise_not_num)

Output:

Original Number: -5
Inverted Number: 9

Practice Questions

  1. Write a function that takes an integer number n and returns the bitwise complement of its binary representation (i.e., flip all bits).
  1. Implement a function to check if a given number is even or odd using only bitwise operators.
  1. Given two integers a and b, write a function that swaps their values without using temporary variables, and also without using the swap_without_temp() function provided earlier in this lesson.
  1. Write a function that returns the binary representation of an integer number using only bitwise operators.
  1. Given two integers a and b, write a function that determines whether they have any common set bits (i.e., bits that are set to 1 in both numbers).
  1. Write a function that calculates the Hamming distance between two binary strings of equal length, using only bitwise operators.
  1. Implement a function that finds all the set bits (bits that are set to 1) in an integer number using only bitwise operators.
  1. Write a function that counts the number of trailing zeros in an integer number using only bitwise operators.
  1. Given two integers a and b, write a function that determines whether they have any common set bits (i.e., bits that are set to 1 in both numbers) without using the AND operator (&).

FAQ

What is the difference between the bitwise NOT operator (~) and the logical NOT operator (not) in Python?

The bitwise NOT operator flips each bit of its operand, while the logical NOT operator returns True if its operand is falsy (i.e., False, 0, None, empty strings, etc.) and False otherwise.

Can I use the bitwise NOT operator on floating-point numbers in Python?

No, the bitwise NOT operator can only be applied to integers. Attempting to use it with floating-point numbers will result in a TypeError.

Is there any performance advantage to using the bitwise NOT operator over other methods for swapping two variables in Python?

While the bitwise NOT operator provides an interesting and educational alternative for swapping variables, it may not offer significant performance benefits in most practical scenarios. In fact, the additional calculations required by the bitwise method can sometimes lead to slower execution times compared to using a temporary variable or other methods such as assignment swaps (a = b; b = a). However, understanding and mastering bitwise operators can still be valuable for solving certain problems more efficiently or debugging complex issues.

What is the significance of the most significant bit (MSB) when working with signed integers in Python?

In Python, the MSB of a signed integer indicates the sign of the number. If the MSB is 0, the number is positive; if it's 1, the number is negative. The bitwise NOT operator changes the sign of the number by flipping the most significant bit.

How can I determine whether an integer number is a power of 2 using only bitwise operators?

To check if an integer n is a power of 2, you can use the following approach:

def is_power_of_two(n):
return n > 0 and ((n & (n - 1)) == 0)

This function works by using the bitwise AND operator with n and n - 1. If n is a power of 2, both numbers will have the same set bits, and the result of the AND operation will be zero.

Python Bitwise NOT Operator (~) | Python | XQA Learn