What is the difference between `bitCount()` and `bitLength()` of a `BigInteger`

A quick demonstration:

public void test() {
    BigInteger b = BigInteger.valueOf(0x12345L);
    System.out.println("b = " + b.toString(2));
    System.out.println("bitCount(b) = " + b.bitCount());
    System.out.println("bitLength(b) = " + b.bitLength());
}

prints

b = 10010001101000101

bitCount(b) = 7

bitLength(b) = 17

So, for positive integers:

bitCount() returns the number of set bits in the number.

bitLength() returns the position of the highest set bit i.e. the length of the binary representation of the number (i.e. log2).

Tags:

Java