Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if all bits in BitSet are set to true

Tags:

java

bitset

I'm using a BitSet in my application and would like to check with a method if all used bits in the BitSet are set to true. Now, I know of the method isEmpty() that checks if all bits are set to false, however I can't seem to find the positive case. I'm aware I could do something like someBitSet.cardinality() == someBitSet.size(), but this seems clumsy. Am I missing something or is there an explicit reason why such a method is not implemented but the opposite case is?

like image 255
conipo Avatar asked Mar 30 '16 12:03

conipo


People also ask

How do you check if all bits are set in a BitSet?

If the loop terminates without returning 'No', then all bits are set in the binary representation of n.

Which BitSet method tests whether all bits from BitSet are set or not?

Member functions Tests whether all bits from bitset are set or not.

How do you know if all bits are zero?

The circuit for checking if all bits are zero is a NOR gate with all the bits of the vector as inputs. The output will be set to '1' only if all the input bits are interpreted as '0' , that's how a NOR gate works.

How do I convert BitSet to all bits to 1?

bitset::set() is a built-in STL in C++ which sets the bit to a given value at a particular index. If no parameter is passed, it sets all bits to 1. If only a single parameter is passed, it sets the bit at that particular index to 1.


1 Answers

There's no thing like "all bits in BitSet", because at any time you can set the bit which is greater than the maximal bit set so far. Suppose that you want to keep in BitSet up to 10 values. So you set 10 bits and want to check whether all of them are true. However BitSet does not know that you have only 10 bits. What if you have more? Next time you can call bitSet.set(10000) and it will work (BitSet will resize automatically).

Note that bitSet.size() is not very helpful in general case: it's about consumed memory. Current implementation is always a multiple of 64, so if you have only 10 different states, someBitSet.cardinality() == someBitSet.size() will always return false. Even if you created the BitSet with new BitSet(10). The constructor parameter is just a desired initial capacity (like in ArrayList). It's used as performance hint only.

The best solution from the performance point of view is to check nextClearBit(0) >= myLength where myLength is the maximal number of values you want to store in BitSet (you should keep it by yourself). This may work faster than cardinality() if the result is false.

like image 105
Tagir Valeev Avatar answered Sep 20 '22 06:09

Tagir Valeev