先頭から続く0の数 Count Leading Zeros
#ビット演算 で、値の先頭から続く0のビットの数を数えたい。
Count Leading Zero #CLZ <-> #CTZ 末尾に続く0の数 Count Trailing Zeros
組み込み関数を使う
code:c++
#ifdef _MSC_VER
#include <intrin.h>
#else
#include <x86intrin.h>
#endif
#ifdef __GNUC__
__builtin_clzll(x)
__builtin_clz(x)
#else
_lzcnt_u64(x)
_lzcnt_u32(x)
#endif
https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#techs=Other&text=_lzcnt_u64&ig_expand=6906,4196
https://gcc.gnu.org/onlinedocs/gcc-4.3.3/gcc/Other-Builtins.html#Other-Builtins
ビット演算で書く
code:c++
int clz(int64_t x){
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >> 16);
x = x | (x >> 32);
return pop_count_ull(~x);
}
↑1のビットを右に伝播させて、0のビットの数を数える(反転させて1のビットを数える)
#1のビットを数える_popcount #popcount
CUDA C++で書く
code:cuda c++
__clzll(x)