Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java BitSet with trailing zeros

How do I work with BitSet for bit representations ending with 0s?

For example, to represent "10100" in BitSet, I'm doing the following.

BitSet bits = new BitSet(5);
bits.set(0);
bits.set(2);

Based on the Java Doc,

length() - Returns the "logical size" of this BitSet: the index of the highest set bit in the BitSet plus one.

size() - Returns the number of bits of space actually in use by this BitSet to represent bit values.

So, for the given example length() returns "3" and size() returns "64" as BitSet internally works with long.

With the given BitSet, how can I determine the actual bits (10100 in this case) in it?

P.S: I'm working on compression techniques and I don't want to use boolean[] to represent it, as each entry in the array can take 1 byte.

Thank you!

like image 642
user2492286 Avatar asked May 02 '26 17:05

user2492286


1 Answers

In a BitSet, the zero index is the least significative bit. Your example should be:

BitSet bits = new BitSet(5);
bits.set(2);
bits.set(4);

Now bits.length() returns 5, as expected.

like image 73
Óscar López Avatar answered May 05 '26 07:05

Óscar López