The following function creates a CFBitVectorRef
that is the bitwise AND of two bitmaps. The function assumes that both bitmaps have the same size count
(which is true in your case, as you said in a comment).
The function creates a (mutable) copy of the first bitmap and then clears all bits that are zero in the second bitmap.
CFBitVectorRef CreateBitmapAnd(CFBitVectorRef bm1, CFBitVectorRef bm2, CFIndex count)
{
CFMutableBitVectorRef result = CFBitVectorCreateMutableCopy(NULL, count, bm1);
for (CFIndex i = 0; i < count; i++) {
if (CFBitVectorGetBitAtIndex(bm2, i) == 0)
CFBitVectorSetBitAtIndex(result, i, 0);
}
return result;
}
In contrast to the proposed solution to How to bitwise-and CFBitVector, this function does not use the internal representation of bitmaps.
A different implementation is the following:
CFBitVectorRef CreateBitmapAnd(CFBitVectorRef bm1, CFBitVectorRef bm2, CFIndex count)
{
size_t nbytes = (count + 7)/8;
UInt8 *bytes1 = malloc(nbytes); // (Error checking omitted)
UInt8 *bytes2 = malloc(nbytes);
CFBitVectorGetBits(bm1, CFRangeMake(0, count), bytes1);
CFBitVectorGetBits(bm2, CFRangeMake(0, count), bytes2);
for (size_t i = 0; i < nbytes; i++) {
bytes1[i] &= bytes2[i];
}
CFBitVectorRef result = CFBitVectorCreate(NULL, bytes1, count);
free(bytes1);
free(bytes2);
return result;
}
The advantage is that it operates on bytes instead of bits (and this could be further optimized to operate on ints), the disadvantage is that memory needs to be allocated and freed.