Home >Backend Development >Python Tutorial >Why does ~2 equal -3 in Python?
Understanding Python's Bitwise Complement Operator (~ Tilde)
Introduction
The bitwise complement operator (~) is a powerful tool in Python that performs a bitwise operation on a numeric value. It's commonly used to invert the bits of a number, which can have interesting effects on the value's representation.
Why ~2 Equals -3
One of the intriguing aspects of the bitwise complement operator is its behavior when applied to the number 2. The result of ~2 is -3. To understand why this happens, we must examine the concept of two's complement.
Two's Complement
In computer systems, negative numbers are typically represented using the two's complement method. In two's complement, a negative value is obtained by inverting the bits of its positive counterpart and adding one.
For example,
Bitwise Complement ~2
When the bitwise complement operator is applied to 2, it simply inverts every bit in the binary representation of 2. The inverted bits, when interpreted in two's complement, represent -3.
Steps:
Operator's Function
The primary function of the complement operator (~) is to flip bits. However, the interpretation of the resulting bit pattern is determined by the underlying machine or context within which the operator is being used.
Remember:
The above is the detailed content of Why does ~2 equal -3 in Python?. For more information, please follow other related articles on the PHP Chinese website!