How to find the position of the only-set-bit in a 64-bit value using bit manipulation efficiently?

后端 未结 9 1732
有刺的猬
有刺的猬 2020-12-24 05:51

Just say I have a value of type uint64_t seen as sequence of octets (1 octet = 8-bit). The uint64_t value is known containing only one set bit<

9条回答
  •  臣服心动
    2020-12-24 06:21

    The value mod 0x8C yields a unique value for each of the cases.

    This value mod 0x11 is still unique.

    The second value in the table is the resulting mod 0x11.

    128 9
    32768   5
    8388608 10
    2147483648  0
    549755813888    14
    140737488355328 2
    36028797018963968   4
    9223372036854775808     15
    

    So a simple lookup table will suffice.

    int find_bit(uint64_t bit){ 
      int lookup[] = { the seventeen values };
      return lookup[ (bit % 0x8C) % 0x11];
    }
    

    No branching, no compiler tricks.

    For completeness, the array is

    { 31, 0, 47, 15, 55, 0, 0, 7, 23, 0, 0, 0, 39, 63, 0, 0}
    

提交回复
热议问题