Search code examples
objective-cbit-manipulationequivalentbitvector

How do I compare two bit vectors for equivalence?


What's the most efficient way to compare two bit vectors? In Objective-C, I'm using CFBitVectors and simply comparing each bit in both:

for (CFIndex bitIndex = 0; bitIndex < numBits; bitIndex++) {
    if (CFBitVectorGetBitAtIndex(thisVector, bitIndex) != CFBitVectorGetBitAtIndex(thatVector, bitIndex)) {
        return NO;
    }
}
return YES;

Which works fine, but I wasn't sure if there wasn't some more efficient way to do it using bit operators.


Solution

  • One can do a bitwise-or operation on the two CFBitVectorRef structs as described in this answer. However, that's subject to failure at a future time, since it's implementation-dependent. The safest way to compare them appears to be one bit at a time as described in the OP. Here's a utility function that does the whole thing:

    BOOL CFBitVectorEqualsCFBitVector(CFBitVectorRef thisVector,  CFBitVectorRef thatVector) {
        CFIndex numBits = CFBitVectorGetCount(thisVector);
        if (numBits != CFBitVectorGetCount(thisVector)) return NO;
        for (CFIndex bitIndex = 0; bitIndex < numBits; bitIndex++) {
            if (CFBitVectorGetBitAtIndex(thisVector, bitIndex) != CFBitVectorGetBitAtIndex(thatVector, bitIndex)) {
                return NO;
            }
        }
        return YES;
    }