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 the second complement , the leading bit is what is called the sign bit . It represents a negative number which is the negative of [ two to the power of (number of bits - one )] .The other bits represent positive numbers .
|
1 2 3 4 5 6 7 8 9 10 11 |
# example number of bits 3 2 1 0 o o o -4 2 1 # 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**(1)] = 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 .
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# example number of bits 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 zero and the zeroes will become one . As such for any number , its ones’ complement plus the number itself will be a series of 1
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# example number of bits : 3 # 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 minus one. As such , a number plus its ones’ complement is always equal to minus one. So to get the ones’ complement of a number o , when using the second complement representation , we just need to apply the formula
|
1 2 3 4 5 6 |
#ones' complement + original number = -1 ō + o = -1 #hence ones' complement is equal to ō = -1 - o |
for example
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
>>> ~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 |