Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Count number of bits set in a java.util.BitSet

Tags:

java

bitset

Any quick method to count the number of set bits in a BitSet other than the usual 'keep a counter' method?

like image 818
Rnet Avatar asked Feb 03 '11 06:02

Rnet


People also ask

How many bits are in a BitSet?

Bitset internally uses long (64 bits).

What is the use of count () function in BitSet?

bitset::count() is an inbuilt STL in C++ which returns the number of set bits in the binary representation of a number. Parameter: The function accepts no parameter. Return Value: The function returns the number of set bits.

What is the use of BitSet in Java?

BitSet is a class defined in the java. util package. It creates an array of bits represented by boolean values. The size of the array is flexible and can grow to accommodate additional bit as needed.


2 Answers

The cardinality() method returns the number of set bits.

like image 141
pwc Avatar answered Nov 16 '22 02:11

pwc


(Assuming you don't want to call cardinality())

int count = 0; 
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) {
    count++;
}

see javadoc

like image 26
Ron Avatar answered Nov 16 '22 02:11

Ron