Mangat Rai Modi - 6 months ago 45

Java Question

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

are logical operators

Update: just found that

Answer

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;
}
```