Java – How to make BitSet not simplified [JAVA]

How to make BitSet not simplified [JAVA]… here is a solution to the problem.

How to make BitSet not simplified [JAVA]

I’m using BitSet to represent possible lecture times, the case is that when you set the corner bits to false, they are simplified, meaning they are no longer in the bitset. How do you make BitSet unsimplified?

To make my explanation clearer, here is the code:

   for(Map.Entry<GrupAssig, BitSet> entry : bitsetPerGrup.entrySet()){

BitSet bitset = entry.getValue();

n franges per dia
            int numFranges = UnitatDocent.getNumFranges();
            int indexDia = this.dia.id() * numFranges;

bitset.clear(indexDia, indexDia+numFranges);
     }

Suppose bitset defaults to 60 bits, numFranges=12 and this.dia.id()=4. This sets the last twelve bits to 0. The result I got was:

11111111111111111111111111111111111111111111111

But if this.dia.id()=3 I get:

11111111111111111111111111111111111100000000000011111111111

You can print BitSet:

    public static void printBitset(BitSet b) {
        StringBuilder s = new StringBuilder();
        for( int i = 0; i < b.length();  i++ )
        {
            s.append( b.get( i ) == true ? 1 : 0 );
        }

System.out.println( s );
    }

This proves what I’m talking about.

Thank you.

Solution

This is the documentation for BitSet.length:

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

If you need to print out a certain number of bits (e.g. 60), use constants instead of “.length()” in your loop. You can call “.get(index)” on any index, regardless of the length, and it will give you the result for that bit.

For example, the following code generates “0000011000”:

import java.util.BitSet;

public class Main {

public static void main(String[] args) {
        BitSet bits = new BitSet();
        bits.set(5);
        bits.set(6);
        StringBuilder bitString = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            bitString.append(bits.get(i) ? "1" : "0");
        }
        System.out.println(bitString.toString());
    }
}

Related Problems and Solutions