The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.util  [50 examples] > Bits  [2 examples]

e363. Performing Bitwise Operations on a Bit Vector

The BitSet class implements a bit-vector of an arbitrary size. It automatically grows dynamically. This example demonstrates how to create and use a BitSet.

The BigInteger class also support bitwise operations (see e129 Performing Bitwise Operations with BigInteger). However, a BigInteger object is immutable where a BitSet is mutable.

    // Create the bitset
    BitSet bits = new BitSet();
    
    // Set a bit on
    bits.set(2);                        // 100 = decimal 4
    
    // Retrieving the value of a bit
    boolean b = bits.get(0);            // false
    b = bits.get(2);                    // true
    
    // Clear a bit
    bits.clear(1);
    
    // Setting a range of bits
    BitSet bits2 = new BitSet();
    bits2.set(1, 4);                    // 1110
    
    // And'ing two bitsets
    bits.and(bits2);                    // 0100
    
    // Xor'ing two bitsets
    bits.xor(bits2);                    // 1010
    
    // Flip all bits in the bitset
    bits.flip(0, bits.length());        // 0101
    
    // Andnot'ing two bitsets
    bits.andNot(bits2);                 // 0001
    
    // Or'ing two bitsets
    bits.or(bits2);                     // 1111

 Related Examples
e364. Converting Between a BitSet and a Byte Array

See also: Arrays    Collections    Dates    Hash Tables    Lists    Property Files    Sets    Sorted Collections    Time    Timers   


© 2002 Addison-Wesley.