Java: BitSet comparison -
suppose have 2 bitset objects in java values as
//<msb....lsb> b1:<11000101> b2:<10111101>
how can compare b1 , b2 know value represented b1 greater b2.
are logical operators (>,<,==) overloaded bitset? or have write own implementation?
update: found "the operator > undefined argument type(s) java.util.bitset, java.util.bitset". there built-in way so?
you can xor
-ing 2 sets together, , comparing length
of result lengths of bit sets:
- if
xor
empty, bit sets equal. can bypass operation callingequals()
- otherwise, length of
xor
result equal position of significant bit different between 2 values. - whichever of 2 operands has bit set greater 1 of two.
here 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; }
Comments
Post a Comment