Fastest way to scan for bit pattern in a stream of bits

后端 未结 13 1810
悲哀的现实
悲哀的现实 2020-12-07 13:38

I need to scan for a 16 bit word in a bit stream. It is not guaranteed to be aligned on byte or word boundaries.

What is the fastest way of achieving this

13条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 14:31

    For a general-purpose, non-SIMD algorithm you are unlikely to be able to do much better than something like this:

    unsigned int const pattern = pattern to search for
    unsigned int accumulator = first three input bytes
    
    do
    {
      bool const found = ( ((accumulator   ) & ((1<<16)-1)) == pattern )
                       | ( ((accumulator>>1) & ((1<<16)-1)) == pattern );
                       | ( ((accumulator>>2) & ((1<<16)-1)) == pattern );
                       | ( ((accumulator>>3) & ((1<<16)-1)) == pattern );
                       | ( ((accumulator>>4) & ((1<<16)-1)) == pattern );
                       | ( ((accumulator>>5) & ((1<<16)-1)) == pattern );
                       | ( ((accumulator>>6) & ((1<<16)-1)) == pattern );
                       | ( ((accumulator>>7) & ((1<<16)-1)) == pattern );
      if( found ) { /* pattern found */ }
      accumulator >>= 8;
    
      unsigned int const data = next input byte
      accumulator |= (data<<8);
    } while( there is input data left );
    

提交回复
热议问题