Fast search of some nibbles in two ints at same offset (C, microoptimisation)

前端 未结 6 880
囚心锁ツ
囚心锁ツ 2021-02-09 01:16

My task is to check (>trillions checks), does two int contain any of predefined pairs of nibbles (first pair 0x2 0x7; second 0xd 0x8). For example:

bit offset:           


        
6条回答
  •  渐次进展
    2021-02-09 02:05

    There are tricks for testing for a zero byte in a word (see e.g. http://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord); a fast method is to use this expression:

    (x - 0x01010101) & ~x & 0x80808080
    

    which evaluates to some non-zero value if any of the 4 bytes within the 32-bit word are 0, or 0 otherwise.

    This method can be adapted to work here:

    static inline int nibble_check(uint32_t A, uint32_t B)
    {
      uint32_t tmp1, tmp2;
    
      tmp1 = (A ^ 0x22222222) | (B ^ 0x77777777);
      tmp2 = (A ^ 0xffffdffffffffd) | (B ^ 0x88888888);
    
      return !!(((tmp1 - 0x11111111) & ~tmp1 & 0x88888888) |
                ((tmp2 - 0x11111111) & ~tmp2 & 0x88888888));
    }
    

提交回复
热议问题