The Ones’ complement operator ~ in python a tutorial

 

The ones’ complement operator ~ , will flip the bits of an integer , so one will become zero , and zero will become one. An integer in python , has :

  • an unlimited number of bits .
  • is represented by its second complement .

In second complement , the leading bit , is what is called a sign bit . It represents a negative number , which is the negative of [ two to the power of (number of bits – one )] . This can also be written like this : -1 * 2^(number of bits - 1 ) .

# Example number of bits is 3 
 2    1    0
 o    o    o 
-4    2    1

# The leading bit is 2 .
#   When it is 1 it is the negative number -[2**(3 - 1 ) ] = -4
# The other bits represent positive numbers :
#   bit 1 represent [2**(1 ) ] = 2
#   bit 0 represent [2**(0 ) ] = 1

For positive numbers , the sign bit is always zero , and for negative numbers , the sign bit is always one . To get the number represented , using second complement , we just have to sum the digits , multiplied by their power , in base two .

# Example number of bits is 3 
 2 1 0 
 1 0 1 
-4 2 1 
# The number is 101 , it is equal to 
# 1 * 2**0 +  0 * 2**1 + 1 * (-1 ) * (2**2 )
# = -4 + 1 = -3


# Example number of bits 3 
 2 1 0 
 0 1 0 
-4 2 1 
# The number is 010 , it is equal to 
# 0 * 2**0 +  1 * 2**1 + 0 * (-1 ) * (2**2 )
# = 0 + 2 + 0 = 2

The ones’ complement operator , will flip the bits of a number , so the ones will become zeroes , and the zeroes will become ones . As such for any number , its ones’ complement , plus the number itself , will be a series of 1 .

# Example number of bits is 3 
# The first bit , is the sign bit : -[2**(3-1 ) ] = -4

# Example 1 
 1 1 1   #  -1 = -4 + 2 + 1 
+
 0 0 0   #   0 = 0 + 0 + 0
 -----     ----
 1 1 1      -1

# Example 2 
 1 0 1   #  -3 = -4 + 0 + 1
+
 0 1 0   #   2 = 2
 -----     ----
 1 1 1      -1

When using the second complement representation of a number , this series of ones , has always a value of : -1 . As such , a number plus , its ones’ complement , is always equal to : -1. So to get the ones’ complement , of a number o , when using the second complement representation , we just need to apply the formula :

# Ones' complement + original number = -1
ō + o = -1

# Hence ones' complement is equal to 
ō = -1 - o

For example :

>>> ~1
-2 
# The ones' complement of 1 is -1 - 1 = -2

>>> ~0
-1
# The ones' complement of 0 is -1 - 0 = -1


>>> ~-5
4
# the ones' complement of -5 is -1 -(-5) = 4