campusx-official / dsmp-2022-23

All the codes and tasks taught in the CampusX Data Science Mentorship Program 2022-23
7 stars 1 forks source link

Bitwise not in python #4

Open samp-suman opened 2 years ago

samp-suman commented 2 years ago

Why ~3 == -4, not 4?

samp-suman commented 2 years ago

Answer is- not is performed bitwise so if x=3 in binary it will be 00000011 which on complementing will be 11111100. When the value of this number is printed as a decimal integer, its base-10 value is assigned to the output.

Now as python number is signed so it will be negative and positive both and signed numbers are stored as two's complement. That is, the above bit pattern, when converting to base10 for storage in two's complement, requires that the complement of the bit pattern be taken, except the first bit remains as it is because this is taken as sign bit: 10000011

Then 1 is added to the bit pattern: 10000100

This pattern, when converted to base10, is -4.

Note: First bit is taken as sign bit, if it's 1 meaning number is negative, otherwise positive.

Further reading- https://webhelp.esri.com/arcgiSDEsktop/9.3/body.cfm?tocVisable=1&ID=-1&TopicName=How%20Bitwise%20Not%20works