I came across many coding sites about bitset. But i cant understand whether it stores bits or integers.
BitSet creates an array of bits represented by boolean values.
import java.util.*;
public class GFG
{
public static void main(String[] args)
{
BitSet bs1 = new BitSet();
BitSet bs2 = new BitSet(6);
bs1.set(0);
bs1.set(1);
bs1.set(2);
bs1.set(4);
bs2.set(4);
bs2.set(6);
bs2.set(5);
bs2.set(1);
bs2.set(2);
bs2.set(3);
System.out.println("bs1 : " + bs1);
System.out.println("bs2 : " + bs2);
}
}
Output:
bs1 : {0, 1, 2, 4}
bs2 : {1, 2, 3, 4, 5, 6}
BitSet stores bits or integers?
How does it stores that in memory?
How the values change when any manipulation is done?
Typically BitSet
would be implemented using a long[]
. Each long
stores 64 consecutive possible bit positions. The array needs a size equal to the highest set bit index minus one (to allow for index 0), divided by 64 (rounded down). Set bits are represented as a binary 1 and bits present in the array but not set as a binary 0.
So the internal representation of your examples would be something like:
bs1 = new long[] { 0b00010111L }; // 23
bs2 = new long[] { 0b01111110L }; // 126
// bit indexes: 76543210
(Bits 8-63 elided from constants - add all the zeros if your want.)