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 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 .

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 .

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

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

for example

Leave a Reply

Your email address will not be published. Required fields are marked *