了解 Java BitSet class 的实现

Understanding the implementation of Java BitSet class

当我尝试对其进行测试并理解它时,BitSet 对象提供的结果有些不清楚。

主要内容:

byte f = (byte)0b00101000;
byte s = (byte)0b11111111;
byte[] bytes = new byte[]{f, s};
BitSet bs = BitSet.valueOf(bytes);

printlnLog("Input bitset: " + bs);
printlnLog("Input bitset length: " + bs.size());

输出:

Input bitset: {3, 5, 8, 9, 10, 11, 12, 13, 14, 15}
Input bitset length: 64

输出对我来说毫无意义。我不明白 BitSet 的底层逻辑。我会感谢你的帮助!

够清楚了吧?

byte f = (byte)0b00101000;
// Bits 0 to 7   --5-3---                  
byte s = (byte)0b11111111;
// Bits 8 to 15  54321098
byte[] bytes = new byte[]{f, s};
BitSet bs = BitSet.valueOf(bytes);

而 64 是由于当前分配的位数。调用bs.length().

可以得到set bits的最大位数

没有任何内容指示任何构造函数或方法定义的尾随未设置位,但这不是必需的。这并没有什么坏处,因为您不会因为使用一个值超过 BitSet 的这个或那个 "end" 的索引(例如 BitSet.get(int index))而受到惩罚。