Search code examples
javabitset

Java BitSet size larger then nbits set in Constructor


I am creating a BitSet with a fixed number of bits. In this case the length of my String holding the binary representation is 508 characters long.

So I create BitSet the following way:

BitSet bs = new BitSet(binary.length());
// binary.length() = 508

But looking at the size of bs I always get a size of 512. I can see that there are always 4 Bits with value of 0 appended at the end.

Maybe there is some misunderstanding of the following documentation:

BitSet(int nbits)

Creates a bit set whose initial size is large enough to explicitly represent bits with indices in the range 0 through nbits-1.

Is it that BitSet always enhances its size so that its size is powers of 2 or why is it larger?


Solution

  • The number of bits in the constructor is a sizing hint, not a limit on the number of bits allowed. The size() of a Bitset is effectively its current capacity, though the specification is rather more rubbery than that.

    So I can't rely on the size if I get passed another bitset? There may also be some bits appended or it can be longer than "expected" ?

    Correct, and yes.

    If you want the logical size (i.e. the highest bit index that is set) use the length() method, not the size() method.

    If length() gives me the highest bit set, this can't help in every situation. Because "my" highest bit on position 508 can also be 0.

    In this case "set" means "set to 1 / true". So if your highest bit (at position 508) is a zero, the length() will be less than 508. I'm not sure if that will help. But if you have a concept of a highest bit position that is defined then you need to represent that position as a separate value.

    A Bitset is actually modelled as a potentially infinite array of bits which is default initialized to all zeros. (That's why there is no "flip the entire Bitset" operation. It would use a huge amount of storage.)