Junior — Middle
Explain the principle of operation of a bit map and how it is used to represent data
sobes.tech AI
Answer from AI
A bitset is a data structure that stores a set of bits (0 or 1), where each bit corresponds to a specific element or state. It is used for compactly representing a set or flags.
How it works:
- Each bit in the bitset represents the presence (1) or absence (0) of an element.
- An array of integers is used for storage, where each bit of a number is a separate flag.
- Bit operations (set, reset, check) are performed quickly using bitwise operations (AND, OR, XOR, shifts).
Applications:
- Efficient storage of large sets with boolean attributes.
- Fast union, intersection, and difference operations on sets.
- Used in algorithms for filtering, searching, indexing.
Example in Java:
import java.util.BitSet;
public class BitSetExample {
public static void main(String[] args) {
BitSet bitSet = new BitSet();
bitSet.set(2); // Set bit at index 2
bitSet.set(4);
System.out.println("Is bit 2 set? " + bitSet.get(2)); // true
System.out.println("Is bit 3 set? " + bitSet.get(3)); // false
bitSet.clear(2); // Reset bit 2
System.out.println("Bit 2 after reset: " + bitSet.get(2)); // false
}
}
Thus, a bitset allows efficient storage and processing of boolean data with minimal memory usage.