In all modern computers, the 2's complement binary is used for representing integers (and not the classical binary representation).
As confirmed in Python docs:
A two's complement binary is same as the classical binary
representation for positive integers but is slightly different for
negative numbers. Negative numbers are represented by performing the
two's complement operation on their absolute value.
The 2's complement of a negative number, -x, is written using the bit pattern for (x-1) with all of the bits complemented (switched from 1 to 0 or 0 to 1).
Example:
2's complement of -15:
-15 => complement(x-1) => complement(15-1) => complement(14) => complement(1110) => 0001
Python's ~ (bitwise NOT) operator returns the 1's complement of the number.
Example:
print(~14) # Outputs -15
14 is (1110) in its 2's complement binary form.
Here, ~14 would invert (i.e. 1's complement) all the bits in this form to 0001.
However, 0001 is actually the 2's complement of -15.
A simple rule to remember the bitwise NOT operation on integers is -(x+1).
print(~60) # Outputs -61
print(~-60) # Outputs 59