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

__always one . To__

*sign bit is*__represented , using second complement , we just have to sum the digits , multiplied by their power , in base two .__

*get the number*# 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