0

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.

Roecrew
  • 1,022
  • 3
  • 17
  • 34
theory
  • 8,210
  • 8
  • 50
  • 115
  • 1
    Depending on how many bits you have, why not call `CFBitVectorGetBits` and dump them into a zeroed unsigned `int` or `long`, and just compare for equality? – Crowman Apr 24 '14 at 00:32
  • Please remove the "C" tag. This has nothing to do with C. – R.D. Apr 24 '14 at 00:56
  • @r-d the code is C, I expect the answer would be, too. So, confused by your comment. – theory Apr 24 '14 at 02:48
  • @r-d Scratch my previous comment. I forgot that the vector object is opaque, with no direct access to the underlying bit array. So yeah, not so C-ish in this case. – theory Apr 24 '14 at 03:00
  • @PaulGriffiths I can have quite large bit vectors, but I suppose I could break them up into 32- or 64-bit parts and compare the integral values. Not sure that would be any more efficient, though, and I expect that code would be less clear. – theory May 12 '14 at 18:56

1 Answers1

0

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;
}
Community
  • 1
  • 1
theory
  • 8,210
  • 8
  • 50
  • 115