Home > Backend Development > Python Tutorial > Why Does `~2` Equal -3 in Python?

Why Does `~2` Equal -3 in Python?

Susan Sarandon
Release: 2024-11-18 06:22:01
Original
352 people have browsed it

Why Does `~2` Equal -3 in Python?

Python Bitwise Complement Operator (~~) Explained

The bitwise complement operator (~) in Python performs a bitwise NOT operation on its operand, inverting all the binary bits. This operator is primarily used to represent negative numbers in the system.

How Does the ~ Operator Work?

Negative numbers are stored in the computer's memory using the two's complement notation. In this notation, the sign bit represents whether the number is positive or negative. The remainder of the bits represent the magnitude of the number.

Consider the number -2. In two's complement, it is represented as follows (8 bits):

1111 1110
Copy after login

This representation is derived by taking the binary complement of the positive counterpart (2) and adding one.

0000 0010 (positive 2) -> 1111 1101 (complement) -> 1111 1110 (add one for negative)
Copy after login

How ~2 Equals -3

To understand why ~2 equals -3, let's examine the bitwise complement of 2:

0000 0010 (positive 2) -> 1111 1101 (complement)
Copy after login

This complement is the two's complement representation of -3:

0000 0011 (positive 3) -> 1111 1100 (complement) -> 1111 1101 (add one for negative)
Copy after login

Therefore, by inverting the bits of 2 using the ~ operator, we obtain the bit pattern that represents -3 in two's complement notation.

Key Point

It is important to note that the ~ operator only performs bitwise inversion. The interpretation of the resulting bits as a positive or negative number is determined by the computer system's memory representation.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template