title: What is the difference between `bitCount()` and `bitLength()` of a `BigInteger`
body: <p>The descriptions of <a href="https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#bitCount()" rel="noreferrer">bitCount()</a> and <a href="https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#bitLength()" rel="noreferrer">bitLength()</a> are rather cryptic:</p>
  
  <blockquote>
    <p>public int <strong>bitCount</strong>()</p>
    
    <p>Returns the number of bits in the two's complement representation of this BigInteger that differ from its sign bit. This method is useful when implementing bit-vector style sets atop BigIntegers.</p>
    
    <p>Returns:
        number of bits in the two's complement representation of this BigInteger that differ from its sign bit.</p>
  </blockquote>
  
  <hr>
  
  <blockquote>
    <p>public int <strong>bitLength</strong>()</p>
    
    <p>Returns the number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit. For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation. (Computes (ceil(log2(this &lt; 0 ? -this : this+1))).)</p>
    
    <p>Returns:
        number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit.</p>
  </blockquote>
  
  <p>What is the real difference between these two methods and when should I use which? </p>
  
  <p>I have used <code>bitCount</code> occasionally to count the number of set bits in a positive integer but I've only rarely use <code>bitLength</code> and usually when I meant <code>bitCount</code> because the differences between the descriptions are too subtle for me to instantly grok.</p>
  
  <p><em>Google Attractor:</em> Java BigInteger bitCount vs bitLength</p>