简体   繁体   English

如何获得BitSet表示的位数?

[英]How do I get the number of bits represented by a BitSet?

If I run the following code: 如果我运行以下代码:

BitSet test = new BitSet(20);
System.out.println("Bitset size is " + test.size());
System.out.println("Bitset length is " + test.length());

I get the output: 我得到的输出:

Bitset size is 64
Bitset length is 0

Which makes sense now that I look closer at the documentation (the former getting the size including implementation overhead and the latter being the last set bit, with all defaulting to false), but is not what I want. 现在,我仔细阅读文档是有道理的(前者的文档大小包括实现开销,而后者是最后一个设置的位,所有默认设置为false),但不是我想要的。

Since the BitSet I actually use can have varying lengths, I want to be able to get back the number of bits represented (ignoring whether they are set). 由于我实际使用的BitSet可以具有不同的长度,因此我希望能够取回表示的位数(忽略是否设置)。 Is there a way to do that (hopefully with a built-in method)? 有没有一种方法(希望使用内置方法)?

I realize I could try flipping all the bits and then doing length, or by tracking the variable I use to instantiate the BitSet, but I feel like both would require several lines of comments with my reasons and I was hoping for something a bit more self-documenting. 我意识到我可以尝试翻转所有位然后执行长度,或者通过跟踪用于实例化BitSet的变量,但是由于我的原因,我觉得两者都需要多行注释,并且我希望自己做些更多的事情-记录。

A BitSet will automatically expand to a size sufficient to represent the highest bit set in it; BitSet将自动扩展到足以代表其中最高位的大小; the initial size is simply a hint as to how many bits you intend to use. 初始大小只是有关您打算使用多少位的提示。 So your question as posed makes no sense. 因此,您提出的问题毫无意义。

我在Mac上进行了一些测试,看来BitSet的长度希望是64的倍数。因此,对于您的BitSet大小为20,它默认为64。如果将大小设置为65,则应该看到一个长度设置为129。将其设置为129应该给您192。这应该给您一种计算“真实” BitSet长度的方法。

Bitset internally uses long (64 bits). 位集在内部使用长(64位)。 So you can determine number of bits needed in multiples of this using the size() method. 因此,您可以使用size()方法确定所需倍数的位数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM