Java 带有尾随零的 BitSet

Java BitSet with trailing zeros

如何使用 BitSet 处理以 0 结尾的位表示?

例如,要在 BitSet 中表示“10100”,我将执行以下操作。

BitSet bits = new BitSet(5);
bits.set(0);
bits.set(2);

基于 Java 文档,

length() - Returns the "logical size" of this BitSet: the index of the highest set bit in the BitSet plus one.

size() - Returns the number of bits of space actually in use by this BitSet to represent bit values.

因此,对于给定的示例 length() returns "3" 和 size() returns "64" 因为 BitSet 在内部使用 long。

对于给定的 BitSet,如何确定其中的实际位(在本例中为 10100)?

P.S: 我正在研究压缩技术,我不想使用 boolean[] 来表示它,因为数组中的每个条目都可以占用 1 个字节。

谢谢!

BitSet 中,零索引是 最低 有效位。你的例子应该是:

BitSet bits = new BitSet(5);
bits.set(2);
bits.set(4);

现在 bits.length() returns 5,如预期。