c++built-inbitcount

32 bit builtin population count for clang counts long long integer c++


I was using the __builtin_popcount with clang compiler and I needed to count a 64 bit number (unsigned long long or uint64_t). From looking it up, __builtin_popcount counts 16 bits, __builtin_popcountl counts 32 bits, and __builtin_popcountll counts 64 bits. When I tested it, __builtin_popcountl was able to do calculations on 64 bit integers. Does anybody know the reason for this?

#include <iostream>

int main() {
    unsigned long long bb = 0b1000000100000001000000010000000100000001000000010000000100000001;
    std::cout << __builtin_popcountl(bb) << std::endl; //returns 9 (correct answer)
}

Solution

  • int __builtin_popcountl (unsigned long) is for unsigned longs.
    int __builtin_popcountll (unsigned long long) is for unsigned long longs.

    unsigned long is 64 bit on your platform, so the conversion from unsigned long long to unsigned long is lossless, and you can use __builtin_popcountl for 64 bit numbers too.

    int is guaranteed to be 16 bits or wider, long is guaranteed to be 32 bits or wider, and long long is guaranteed to be 64 bits or wider. That means you can always use __builtin_popcountl with 32 bit numbers, and you may or may not be able to use it with 64 bit numbers (in this case you could).

    Related question: What is the bit size of long on 64-bit Windows?