raja.genupula
June 5th, 2011, 04:08 AM
Hey Friends
does any one have tried this. open python in terminal .
types as follows
>>>~1
ans:-2
>>>~-1
ans:0
How its going to be done as above .
r-senior
June 5th, 2011, 10:08 AM
It's just the way two's complement (http://en.wikipedia.org/wiki/Two%27s_complement) signed numbers work. The ~ is a bitwise negate.
Simple example with 4 bits:
1 = 0001
~1 = 1110 = -2
-1 = 1111
~-1 = 0000 = 0
The bit in red denotes the sign: 1 means negative, 0 means positive.
The point of two's complement is that you can do the same low-level addition algorithm for positive and negative numbers, i.e. a simple long addition in binary:
(2 + 3 = 5):
0010 +
0011
----
0101 (0 + 1 = 1, 1 + 1 = 0 and 1 carried)
(2 + (-3) = -1):
0010 +
1101
----
1111 (0 + 1 = 1, 1 + 0 = 1, 0 + 1 = 1 and 0 + 1 = 1)
Powered by vBulletin® Version 4.2.2 Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.