Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you take a trivial example of <code>4 (0b0100) + 5 (0b0101)</code> you can see that the unsigned sum should be <code>9 (1001)</code> which is actually <code>-7</code> in two's complement. If you then take that sum (0b1001) and subtract 4 from it using two's complement arithmetic: </p> <pre><code> 0b1001 - 0b0100 = 0b1001 + 2s_complement(0b0100) = 0b1001 + 0b1100 = 0b1_0101 </code></pre> <p>you end up with 0101 which is 5 (you drop the overflowing most significant 1 during a 2's complement operation). Subtracting 5 from the sum equals 4:</p> <pre><code> 0b1001 - 0b0101 = 0b1001 + 2s_complement(0b0101) = 0b1001 + 0b1011 = 0b1_0100 </code></pre> <p>This satisfies the c code you provided but still resulted in an overflow.</p> <p>From wikipedia's article on <a href="http://en.wikipedia.org/wiki/Two%27s_complement" rel="nofollow">two's complement</a>:</p> <pre> Two's complement Decimal 0111 7 0110 6 0101 5 0100 4 0011 3 0010 2 0001 1 0000 0 1111 −1 1110 −2 1101 −3 1100 −4 1011 −5 1010 −6 1001 −7 1000 −8 </pre> <p><strong>Update:</strong><br> To demonstrate your INT_MAX example using my trivial 4 bit integer system with INT_MAX = 7 we can see the same result as your c code. </p> <pre><code> 7 + 7 (0b0111 + 0b0111) = 0b1110 (-2 in two's complement) </code></pre> <p>Just like my example above, subtracting, <code>sum - 7</code> will equal <code>7</code>. </p> <pre><code> 0b1110 - 0b0111 = 0b1110 + 2s_complement(0b0111) = 0b1110 + 0b1001 = 0b1_0111 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload