How to use BitSet with nextSetBit() to find set bits indexes in Java

1 Answer

0 votes
import java.util.BitSet;

public class BitSetDemo {
    public static void main(String[] args) {
        // Create a BitSet with 16 bits
        BitSet bs = new BitSet(16);

        // Set bits at positions 3, 5, 11, and 14
        bs.set(3);
        bs.set(5);
        bs.set(11);
        bs.set(14);

        // Print the BitSet as a binary string
        System.out.println(getBinaryString(bs, 16));

        // Find and print the first set bit
        int firstSetBit = bs.nextSetBit(0);
        System.out.println("First set bit at index: " + firstSetBit);

        // Print all set bit indexes
        System.out.println("All the set bits indexes:");
        for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
            System.out.print(i + " ");
        }
    }

    // Helper method to print BitSet as a binary string
    private static String getBinaryString(BitSet bs, int size) {
        StringBuilder sb = new StringBuilder();
        for (int i = size - 1; i >= 0; i--) {
            sb.append(bs.get(i) ? '1' : '0');
        }
        return sb.toString();
    }
}

 
/*
run:
 
0100100000101000
First set bit at index: 3
All the set bits indexes:
3 5 11 14 
 
*/

 



answered Nov 3 by avibootz
...