~ Binary Ones Complement in Python 3

13,819

Solution 1

~ is a bitwise inversion operator and it acts exectly as defined:

The bitwise inversion of x is defined as -(x+1).

This is simply how the bitwise inversion of the two's complement representation of an integer works.

The two's complement wheel visualizes this pretty well:

enter image description here

As you can see, the bitwise inversion of 1 is -2, the bitwise inversion of 2 is -3, ..., and the bitwise inversion of 60 will be -61.

Solution 2

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

Solution 3

You are almost there. 1100 0011 is actually -61.

Here's how a negative binary is converted to decimal:

  1. Invert the bits

  2. Add 1

  3. Convert to decimal

  4. Add negative sign

So:

1100 0011

0011 1100 <-- bits inverted

0011 1101 <-- one added

       61 <-- converted to decimal

      -61 <-- added negative sign

From wikipedia's Two's complement page:

The two's complement of an N-bit number is defined as its complement with respect to 2^N. For instance, for the three-bit number 010, the two's complement is 110, because 010 + 110 = 1000.

Here 1100 0011's complement is 0011 1101 cuz

    1100 0011
+   0011 1101
-------------
  1 0000 0000 
Share:
13,819
Rahul Mishra
Author by

Rahul Mishra

Updated on June 04, 2022

Comments

  • Rahul Mishra
    Rahul Mishra almost 2 years

    Just had a doubt about how binary one's complement work. For example(in python):

    a = 60
    print(~a)
    

    Gives an output:-

    -61
    

    Isn't binary one's complement of 60 is :

    a = 0011 1100
    ~a  = 1100 0011
    

    Should it not be -60 ?

    I know I'm wrong but why does it shift ahead to -61?

  • nurabha
    nurabha almost 2 years
    2's complement representation of negative integer -15 is 5'b10001. So it needs atleast 5 bits and cannot be done with 4 bits.