title: Why does Integer.bitCount() return 8 for an input of 255?
body: <p>The Java API for <a href="https://docs.oracle.com/javase/10/docs/api/java/lang/Integer.html#bitCount(int)" rel="nofollow noreferrer">Integer.bitCount()</a> tells us:</p>
  
  <p>"public static int bitCount(int i)</p>
  
  <p>Returns the number of one-bits in the two's complement binary representation of the specified int value. This function is sometimes referred to as the population count.</p>
  
  <p>Returns:
      the number of one-bits in the two's complement binary representation of the specified int value.
  Since:
      1.5"</p>
  
  <p>So if we take 255 and convert it to binary, we get 11111111.  If we convert that to the two's complement version we get 00000001, making the number of one-bits one.  However, if I run this code:<br></p>
  
  <pre><code>import java.lang.*;
  
  public class IntegerDemo {
  
  public static void main(String[] args) {
  
      int i = 255;
      System.out.println("Number = " + i);
  
      /* returns the string representation of the unsigned integer value 
      represented by the argument in binary (base 2) */
      System.out.println("Binary = " + Integer.toBinaryString(i));
  
      /* The next few lines convert the binary number to its two's
      complement representation */
      char[] tc= Integer.toBinaryString(i).toCharArray();
      boolean firstFlipped = true;
      for (int j = (tc.length - 1); j &gt;= 0; j--){
          if (tc[j] == '1'){
              if(firstFlipped){
                  firstFlipped = false;
              }
              else{
                  tc[j] = '0';
              }
          }
          else {
              tc[j] = '1';
          }
      }
  
      // Casting like this is bad.  Don't do it. 
      System.out.println("Two's Complement = " + new String(tc));
  
  
      System.out.println("Number of one bits = " + Integer.bitCount(i)); 
      }
  } 
  </code></pre>
  
  <p><br>
  I get this output:<br>
  Number = 255<br>
  Binary = 11111111<br>
  Two's Complement = 00000001<br>
  Number of one bits = 8<br><br></p>
  
  <p>Why am I getting 8 instead of 1?</p>