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

前端 未结 2 987
青春惊慌失措
青春惊慌失措 2021-01-11 19:19

The descriptions of bitCount() and bitLength() are rather cryptic:

public int bitCount()

Returns the number of bits in th

2条回答
  •  孤独总比滥情好
    2021-01-11 20:12

    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).

提交回复
热议问题