This technique counts the number of bits; it loops through once for each bit equal to 1. This is reasonably fast for sparse arrays.
| 85 | // This technique counts the number of bits; it loops through once for each |
| 86 | // bit equal to 1. This is reasonably fast for sparse arrays. |
| 87 | int cRawBitArray::CountBits(const int num_bits) const |
| 88 | { |
| 89 | const int num_fields = GetNumFields(num_bits); |
| 90 | int bit_count = 0; |
| 91 | |
| 92 | for (int i = 0; i < num_fields; i++) { |
| 93 | int temp = bit_fields[i]; |
| 94 | while (temp != 0) { |
| 95 | temp = temp & (temp - 1); |
| 96 | bit_count++; |
| 97 | } |
| 98 | } |
| 99 | return bit_count; |
| 100 | } |
| 101 | |
| 102 | // This technique is another way of counting bits; It does a bunch of |
| 103 | // clever bit tricks to do it in parallel in each int. |