algorithm - Iterating through a bit sequence and finding each set bit -


my question more or less what's in title; i'm wondering if there's fast way going through sequence of bits , finding each bit that's set.

more detailed information:

i'm working on data stucture represents set of objects. in order support operations need, structure must able perform fast intersection of subsets internally. solution i've come have each subset of structure's superset represented "bit array", each bit maps index in array holds superset's data. example: if bit #1 set in subset, element @ index 1 in superset's array present in subset.

each subset consists of array of ulong big enough there's enough bits represent entire superset (if superset contains 256 elements, size of array must 256 / 64 = 4). find intersection of 2 subsets, s1 , s2, can iterate through s1 , s2's array, , find bitwise-and between ulongs @ each index.

now question about: in order return data of subset, have iterate through bits in subset's "bit array" , find bits set. how curently it:

 /// <summary>  /// gets enumerator enables enumeration on strings in subset.  /// </summary>  /// <returns> enumerator. </returns>  public ienumerator<string> getenumerator()  {      int bitarraychunkindex = 0;       int bitarraychunkoffset = 0;       int bitarraychunkcount = this.bitarray.length;        while(bitarraychunkindex < bitarraychunkcount)      {          ulong bitchunk = bitarray[bitarraychunkindex];           // relevant part           if (bitchunk != 0)          {               int bit = 0;               while (bit < bit_array_chunk_size  /* 64 */)               {                    if(bitchunk.bitisset(bit))                         yield return supersetdata[bitarraychunkoffset + bit];                    bit++;               }          }          bitarraychunkindex++;          bitarraychunkoffset += bit_array_chunk_size;           // end of relevant part      }  } 

is there obvious ways optimize this? bit hacks enable done fast? thanks!

on intel 386+, can use machine instruction bitsearchfirst. following - sample gcc. little tricky process 64-bit words, anyway works quick , efficient.

#include <stdio.h> #include <stdlib.h> #include <stdint.h>  int main(int argc, char **argv) {   uint64_t val;   sscanf(argv[1], "%llx", &val);   printf("val=0x%llx\n", val);   uint32_t result;   if((uint32_t)val) { // first bit inside lowest 32     asm("bsfl %1,%0" : "=r"(result) : "r"(val));   } else {             // first bit outside lowest 32     asm("bsfl %1,%0" : "=r"(result) : "r"(val >> 32));     result += 32;   }   printf("val=%llu; result=%u\n", val, result);   return 0; } 

also, in use x64 architecture, can try use bsfq instruction, , remove "if/else"


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -