Skip to content

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:

BitSet.valueOf(new byte[] { 0b100111 })
// {0, 1, 2, 5}

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:

BitSet.valueOf(new byte[] { 0b011000 })
// { 3, 4 }

Answer

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

yourBitSet.flip(0, length);

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:

yourBitSet.flip(0, yourBitSet.length());

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