BigInteger的bitCount()和bitLength()有什么区别 [英] What is the difference between `bitCount()` and `bitLength()` of a `BigInteger`

查看:64
本文介绍了BigInteger的bitCount()和bitLength()有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bitCount()的描述 bitLength()颇为神秘:

public int bitCount ()

返回此BigInteger的二进制补码表示形式中不同于其符号位的位数.在BigIntegers顶部实现位向量样式集时,此方法很有用.

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.

返回:BigInteger的二进制补码表示形式中的位数(不同于其符号位).

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


public int bitLength ()

返回此BigInteger的最小2补码表示形式中的位数,不包括符号位.对于正数BigInteger,这等效于普通二进制表示形式的位数.(计算(ceil(log2(this< 0?-this:this + 1))).)

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

返回:BigInteger的最小2补码表示形式中的位数,不包括符号位.

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

这两种方法之间的真正区别是什么?何时应使用哪种方法?

What is the real difference between these two methods and when should I use which?

我偶尔使用 bitCount 来计数正整数中设置的位数,但是我很少使用 bitLength ,通常当我指的是 bitCount时,因为描述之间的差异太微妙了,我无法立即浏览.

I have used bitCount occasionally to count the number of set bits in a positive integer but I've only rarely use bitLength and usually when I meant bitCount because the differences between the descriptions are too subtle for me to instantly grok.

Google Attractor: Java BigInteger bitCount与bitLength

Google Attractor: Java BigInteger bitCount vs 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

b = 10010001101000101

bitCount(b)= 7

bitCount(b) = 7

bitLength(b)= 17

bitLength(b) = 17

因此,对于正整数:

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

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

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

这篇关于BigInteger的bitCount()和bitLength()有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆