Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is something I have written a while ago for fun. It uses a <a href="http://en.wikipedia.org/wiki/Two%27s_complement" rel="noreferrer">two's complement</a> representation and implements addition using repeated shifts with a carry bit, implementing other operators mostly in terms of addition.</p> <pre><code>#include &lt;stdlib.h&gt; /* atoi() */ #include &lt;stdio.h&gt; /* (f)printf */ #include &lt;assert.h&gt; /* assert() */ int add(int x, int y) { int carry = 0; int result = 0; int i; for(i = 0; i &lt; 32; ++i) { int a = (x &gt;&gt; i) &amp; 1; int b = (y &gt;&gt; i) &amp; 1; result |= ((a ^ b) ^ carry) &lt;&lt; i; carry = (a &amp; b) | (b &amp; carry) | (carry &amp; a); } return result; } int negate(int x) { return add(~x, 1); } int subtract(int x, int y) { return add(x, negate(y)); } int is_even(int n) { return !(n &amp; 1); } int divide_by_two(int n) { return n &gt;&gt; 1; } int multiply_by_two(int n) { return n &lt;&lt; 1; } int multiply(int x, int y) { int result = 0; if(x &lt; 0 &amp;&amp; y &lt; 0) { return multiply(negate(x), negate(y)); } if(x &gt;= 0 &amp;&amp; y &lt; 0) { return multiply(y, x); } while(y &gt; 0) { if(is_even(y)) { x = multiply_by_two(x); y = divide_by_two(y); } else { result = add(result, x); y = add(y, -1); } } return result; } int main(int argc, char **argv) { int from = -100, to = 100; int i, j; for(i = from; i &lt;= to; ++i) { assert(0 - i == negate(i)); assert(((i % 2) == 0) == is_even(i)); assert(i * 2 == multiply_by_two(i)); if(is_even(i)) { assert(i / 2 == divide_by_two(i)); } } for(i = from; i &lt;= to; ++i) { for(j = from; j &lt;= to; ++j) { assert(i + j == add(i, j)); assert(i - j == subtract(i, j)); assert(i * j == multiply(i, j)); } } return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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