@Arun: This is the way two's complement arithmetic works. For any x, - x = ~x + 1. This says that to negate a number, complement it and add 1.
Technically speaking, two's complement is a "weighted code." Each bit position has a certain weight that is added in if the bit in that position is a 1. Counting from the right (low-order bit), the weights are 1, 2, 4, 8, ..., -2^(n-1), where n is the number of bits in the integer. Thus, for example, for 8 bit integers, the weights are 1, 2, 4, 8, 16, 32, 64, and -128. Let b<i> be the ith bit of the number, counting from the right with the low order bit being bit 0. Let w<i> be the weight of the ith bit. Then the value of the number is V = sum from i = 0 to n-1 of (b<i> * w<i>). The value of the complement of the number is ~V = sum from i = 0 to n-1 of ((1 - b<i>) * w<i>), where 1 - b<i> is the complement of bit i, i.e., ~b<i>. Then V + ~V = sum from i = 0 to n-1 of w<i> since b<i> cancels -b<i> for every i. The sum of the weights is -1. Thus, V + ~V = -1, from which -V = ~V + 1. Dave On Sep 18, 5:26 pm, Arun Vishwanathan <[email protected]> wrote: > Hi all, > > When I take negation of an integer in C, 0 is displayed as -1 > ~5 is displayed as -6. > Can some one tell me the logic of how this conversion is happening in C? > > Arun -- You received this message because you are subscribed to the Google Groups "Algorithm Geeks" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/algogeeks?hl=en.
