Search code examples
javabitset

Java: BitSet comparison


Suppose we have two BitSet objects in Java with values as

//<MSB....LSB>
B1:<11000101>
B2:<10111101>

How can we compare B1 and B2 to know that the value represented by B1 is greater than that by B2.

are logical operators (>,<,==) overloaded for BitSet? or Do I have to write my own implementation?

Update: just found that "The operator > is undefined for the argument type(s) java.util.BitSet, java.util.BitSet". Is there any built-in way to do so?


Solution

  • You can do it by xor-ing the two sets together, and comparing the length of the result to lengths of bit sets:

    • If xor is empty, bit sets are equal. You can bypass this operation by calling equals()
    • Otherwise, the length of xor result will be equal to the position of the most significant bit that is different between the two values.
    • Whichever of the two operands has this bit set is the greater one of the two.

    Here is a sample implementation:

    int compare(BitSet lhs, BitSet rhs) {
        if (lhs.equals(rhs)) return 0;
        BitSet xor = (BitSet)lhs.clone();
        xor.xor(rhs);
        int firstDifferent = xor.length()-1;
        if(firstDifferent==-1)
                return 0;
    
        return rhs.get(firstDifferent) ? 1 : -1;
    }
    

    Demo.