title: How to get 2's complement of a binary number in Java programmatically
body: <p>How to calculate the 2's Complement of a Hex number in Android/Java.</p>
  
  <pre><code>    For Example : 
      String x = 10011010;
      1's complement of x = 01100101;
      2's complement is 01100110;
  </code></pre>
  
  <p><em>How I can pro-grammatically achieve in Java?</em></p>
  
  <p>I had tried the following code to convert the binary to its 1's compliment:</p>
  
  <pre><code>public String complementFunction(String bin) {
          String  ones = "";
  
          for (int i = 0; i &lt; bin.length(); i++) {
              ones += flip(bin.charAt(i));
          }
          return ones;
      }
  
  // Returns '0' for '1' and '1' for '0'
      public char flip(char c) {
          return (c == '0') ? '1' : '0';
      }
  </code></pre>
  
  <p>But I'm not able to get its two's complement.</p>