Counting the number of leading zeros in a 128-bit integer

后端 未结 3 830
日久生厌
日久生厌 2021-01-06 03:40

How can I count the number of leading zeros in a 128-bit integer (uint128_t) efficiently?

I know GCC\'s built-in functions:

  • __builti
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-06 04:41

    inline int clz_u128 (uint128_t u) {
      uint64_t hi = u>>64;
      uint64_t lo = u;
      int retval[3]={
        __builtin_clzll(hi),
        __builtin_clzll(lo)+64,
        128
      };
      int idx = !hi + ((!lo)&(!hi));
      return retval[idx];
    }
    

    this is a branch free variant. Note that more work is done than in the branchy solution, and in practice the branching will probably be predictable.

    It also relies on __builtin_clzll not crashing when fed 0: the docs say the result is undefined, but is it just unspecified or undefined?

提交回复
热议问题