Skip to content
Advertisement

How to flip all the bits in Java BitSet while preserving its length

How can I flip all the bits in a Java BitSet, while preserving its length?

For example, given the following BitSet:

JavaScript

Is there a simple method to flip all the bits, while preserving the BitSet length (6, in the above example)?

I would like to get:

JavaScript

Advertisement

Answer

BitSet has a flip(from, to) method, which allows you to flip bits in a range:

JavaScript

The question you need to answer, however, is what you actually mean by “length”.

  • A BitSet has the size() method, but that reports the number of bits it has allocated space for – perhaps more than you think the size is.

  • It also has a length() method, which reports the highest-set bit in the bit set – perhaps less than you think the length of the bitset is.

Assuming you’re OK with using length(), you can use:

JavaScript

Of course, since this clears the highest-set bit, yourBitSet will have a smaller length() afterwards.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement