Using a BitSet

The BitSet allows you to work with bits (0 and 1). You can not only get and set bits individually but also perform bitwise operations like and and or. The size of the BitSet may vary. For example, if you initialy set the first bit to 1, 64 bits will be used. Then if you set the bit 100 to 1, the BitSet will grow to 128. The 64 alignment may be different in future implementations.

Operations:

and:   result of (a and b) is 1 if only a and b have the value of 1
or:    result of (a or b) is 1 if at least a or b has the value of 1
xor:   result of (a xor b) is 1 if a or b has the value of 1, but not both

Main.java:

import java.util.*;
 
public class Main {
   public static void main(String args[]) {
      BitSet bs1 = new BitSet();
 
      bs1.set(7);               // sets the 7th bit   00000001000... (64)
      System.out.println(bs1);  // outputs {7}
      bs1.set(5);	        // sets the 5th bit   00000101000... (64)
      System.out.println(bs1);  // outputs {5, 7}
      bs1.clear(7);             //                    00000100000... (64)
      System.out.println(bs1);  // outputs {5}
      
      BitSet bs2 = new BitSet();
      bs2.set(1);               //                    01000000000... (64)
      bs2.set(5);               //                    01000100000... (64)
 
      bs1.and(bs2);             //                    00000100000... (64)
      System.out.println(bs1);  // outputs {5}
 
      bs1.xor(bs2);             //                    01000000000... (64)
      System.out.println(bs1);  // outputs {1}
 
      bs1.or(bs2);              //                    01000100000... (64)
      System.out.println(bs1);  // outputs {1, 5}
   }
}

outputs:

{7}
{5, 7}
{5}
{5}
{1}
{1, 5}