gpt4 book ai didi

java - `bitCount()`的 `bitLength()`和 `BigInteger`有什么区别

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:58:02 24 4
gpt4 key购买 nike

bitCount()的描述和 bitLength()相当神秘:

public int bitCount()

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.

Returns: number of bits in the two's complement representation of this BigInteger that differ from its sign bit.


public int bitLength()

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 < 0 ? -this : this+1))).)

Returns: number of bits in the minimal two's-complement representation of this BigInteger, excluding a sign bit.

这两种方法之间的真正区别是什么?我应该在什么时候使用哪一种?

我偶尔会使用 bitCount 来计算正整数中设置的位数,但我很少使用 bitLength 并且通常当我指的是 bitCount 时 因为描述之间的差异太细微,我无法立即理解。

Google Attractor:Java BigInteger bitCount 与 bitLength

最佳答案

快速演示:

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());
}

打印

b = 10010001101000101

bitCount(b) = 7

bitLength(b) = 17

因此,对于正整数:

bitCount() 返回数字中设置的位数

bitLength() 返回最高设置位的位置 数字的二进制表示的长度(即log2)

关于java - `bitCount()`的 `bitLength()`和 `BigInteger`有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44407351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com