Search code examples
gccc++14built-in

C++ gcc _builtin function gives unexpected answer


Int64_t n=7; after printing __builtin_clz(n) answer is 29 rather than the expected answer 61.


Solution

  • That is the signature for the intrinsic you are using:

    int __builtin_clz (unsigned int x)

    As you can see it works on 32-bit unsigned. It treat your 64 bit integer as a 32 one. Since 7 has 4 bits set it return 32-3 = 29

    Try __builtin_clzl; or __builtin_clzll instead.

    details here