Two's complement: Difference between revisions

Content deleted Content added
No edit summary
Tags: Mobile edit Mobile web edit Advanced mobile edit
Line 182:
The result is a signed binary number representing the decimal value −5 in two's-complement form. The most significant bit is 1, signifying that the value represented is negative.
 
Alternatively, instead of adding 1 after inverting a positive binary number, 1 can be subtracted from the number ''before'' it is inverted. The two methods can easily be shown to be equivalent. The inversion (ones' complement) of <math>x</math> equals <math>(2^N - 1) - x</math>, so the sum of the inversion and 1 equals <math>(2^N - 1) - x + 1 = </math><math>2^N - x - 1 + 1 = </math><math>2^N - x</math>, which equals the two's complement of <math>x</math> as expected. The inversion of <math>x - 1</math> equals <math>(2^N - 1) - (x - 1) = </math><math>(2^N - 1) - x + 1 = </math><math>2^N - x</math>, identical to the previous equation. Essentially, the subtraction inherent in the inversion operation changes the -1−1 added to <math>x</math> before the inversion into +1 added after the inversion. This alternate subtract-and-invert algorithm to form a two's complement can sometimes be advantageous in computer programming or hardware design, for example where the subtraction of 1 can be obtained for free by incorporating it into an earlier operation.<ref>... e.g. by reducing an added constant by 1, increasing a subtracted constant by 1, or setting the carry/borrow flag before a subtract-with-borrow operation. For example, to compute <math>-(m + 4)</math>, instead of adding 4 to <math>m</math>, inverting the result, and then adding 1, one can merely add 3 (= 4 - 1) to <math>m</math> and then invert the result. (Of course, it is also an option, using the invert-and-add scheme, to invert <math>m</math> first and then subtract 3 [equivalent to adding -3−3 = -4−4 + 1].)</ref>
 
The two's complement of a negative number is the corresponding positive value, except in the special case of the [[most negative number]]. For example, inverting the bits of −5 (above) gives: