Working with variable-length bitsets

BitSet implements a vector of bits that grows as needed. Each component of the bit set has a boolean value. The bits of a BitSet are indexed by nonnegative integers.

By default, all bits in the set initially have the value false.

 
import java.util.BitSet;

public class Main {
  public static void main(String[] args) {
    BitSet bs1 = new BitSet();
    bs1.set(1, true);
    bs1.set(2, true);
    bs1.set(3, true);
    bs1.set(4, true);
    BitSet bsTemp = (BitSet) bs1.clone();
    dumpBitset(" ", bs1);
    BitSet bs2 = new BitSet();
    bs2.set(5, true);
    bs2.set(6, true);
    bs2.set(7, true);
    bs2.set(9, true);
    dumpBitset(" ", bs2);
    bs1.and(bs2);
    dumpSeparator(Math.min(bs1.size(), 16));
    dumpBitset("AND (&) ", bs1);
    System.out.println();
    bs1 = bsTemp;
    dumpBitset(" ", bs1);
    dumpBitset(" ", bs2);
    bsTemp = (BitSet) bs1.clone();
    bs1.or(bs2);
    dumpSeparator(Math.min(bs1.size(), 16));
    dumpBitset("OR (|) ", bs1);
    System.out.println();
    bs1 = bsTemp;
    dumpBitset(" ", bs1);
    dumpBitset(" ", bs2);
    bsTemp = (BitSet) bs1.clone();
    bs1.xor(bs2);
    dumpSeparator(Math.min(bs1.size(), 16));
    dumpBitset("XOR (^) ", bs1);
  }

  static void dumpBitset(String preamble, BitSet bs) {
    System.out.print(preamble);
    int size = Math.min(bs.size(), 16);
    for (int i = 0; i < size; i++){
      System.out.print(bs.get(i) ? "1" : "0");
    }
      
    System.out.print(" size(" + bs.size() + "), length(" + bs.length() + ")");
    System.out.println();
  }

  static void dumpSeparator(int len) {
    System.out.print(" ");
    for (int i = 0; i < len; i++){
      System.out.print("-");
    }
      
    System.out.println();
  }
}
  
 
0111100000000000 size(64), length(5)
 0000011101000000 size(64), length(10)
 ----------------
AND (&) 0000000000000000 size(64), length(0)

 0111100000000000 size(64), length(5)
 0000011101000000 size(64), length(10)
 ----------------
OR (|) 0111111101000000 size(64), length(10)

 0111100000000000 size(64), length(5)
 0000011101000000 size(64), length(10)
 ----------------
XOR (^) 0111111101000000 size(64), length(10)
  
Home 
  Java Book 
    Collection  

BitSet:
  1. Working with variable-length bitsets
  2. new BitSet(int size)
  3. BitSet: and(BitSet anotherBitSet)
  4. BitSet: andNot(BitSet set)
  5. BitSet: clone()
  6. BitSet: get(int bitIndex)
  7. BitSet: length()
  8. BitSet: or(BitSet anotherBitSet)
  9. BitSet: set(int bitIndex)
  10. BitSet: size()
  11. BitSet: xor(BitSet anotherBitSet)