Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The ~ (bitwise NOT) operator is a unary operator that performs logical negation on each bit of an integer’s binary representation, flipping 0s to 1s and 1s to 0s. Because Python integers have arbitrary precision and are evaluated using two’s complement arithmetic, applying the ~ operator to an integer x mathematically evaluates to -(x + 1).
result = ~x

Underlying Mechanics and Two’s Complement

Unlike languages with fixed-width integers (e.g., 32-bit or 64-bit), Python integers conceptually possess an infinite number of sign bits. Positive numbers have an infinite sequence of leading 0s, while negative numbers have an infinite sequence of leading 1s. When the ~ operator flips the bits of a positive integer, the infinite leading 0s become infinite leading 1s, transforming the result into a negative number according to two’s complement representation.
x = 5

# Conceptual binary representation (infinite leading zeros):

# ...00000000 00000101

y = ~x

# Bitwise inversion (infinite leading ones):

# ...11111111 11111010

print(y) 

# Output: -6

Mathematical Equivalence

Regardless of the integer provided, the bitwise NOT operation in Python strictly adheres to the following algebraic identity:
~x == -(x + 1)

Data Type Support

The ~ operator is natively supported by the int and bool data types. It is not supported by float, str, or other non-integral built-in types, which will raise a TypeError. Because bool is a subclass of int in Python (True evaluates to 1 and False evaluates to 0), applying the ~ operator to a boolean yields an integer, not a negated boolean.
~True   # Evaluates to -2, because -(1 + 1) = -2
~False  # Evaluates to -1, because -(0 + 1) = -1

Object-Oriented Implementation

At the object level, the ~ operator is mapped to the __invert__() magic method (dunder method). When the Python interpreter encounters ~x, it internally invokes x.__invert__(). You can implement this method in custom classes to define specific behavior for the bitwise NOT operator.
class CustomInt:
    def __init__(self, value):
        self.value = value

    def __invert__(self):
        # Custom implementation of the ~ operator
        return CustomInt(-(self.value + 1))

obj = CustomInt(10)
inverted_obj = ~obj
Master Python with Deep Grasping Methodology!Learn More