gpt4 book ai didi

带有尾随零的 Java BitSet

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

如何使用 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() 返回“3”,而 size() 返回“64”,因为 BitSet 在内部使用 long。

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

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

谢谢!

最佳答案

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

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

现在 bits.length() 返回 5,正如预期的那样。

关于带有尾随零的 Java BitSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42878875/

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