title: two's complement finding algorithm
body: <p>I am trying to see how compiler writes in binary negative numbers, so here is code which  should do it</p>
  
  <pre><code>#include &lt;cstdlib&gt;
  #include &lt;iostream&gt;
  using namespace std;
  void complement(int n)
  {
      int l = n;
      int s = 0;
      int k = 0;
      int m = 0;
  
      while (n != 0)
      {
          s = n  %  2;
          n /= 2;
          cout &lt;&lt; s &lt;&lt; "  ";
      }
  
      cout &lt;&lt; endl;
      m = ~l + 1;
      cout &lt;&lt; m &lt;&lt; endl;
      cout &lt;&lt; endl;
  
      while (m != 0)
      {
          int k = m  %  2;
          m /= 2;
          cout &lt;&lt; k &lt;&lt; "  ";
      }
  }
  
  int main(int argc, char *argv[])
  {
      int n;
      cin &gt;&gt; n;
      cout &lt;&lt; endl;
      complement(n);
      system("PAUSE");
      return EXIT_SUCCESS;
  }
  </code></pre>
  
  <p>but strange is that, when I enter 5, for instance, which clearly in binary form is 101 in 3 bit, its complement -5 is represented -10-1? This is what my code's output shows me, but I know that is it not correct, because 2's complement of any number is given by reversing its bits, 0 by 1 and vice-versa, and then +1, in case of 5(101), -5 will be (010+1)=(011). Please help me, how to correct my code so that, it  could  make complement correctly.</p>