carb::cpp::popcount

Defined in carb/cpp/Bit.h

template<class T, std::enable_if_t<std::is_unsigned<T>::value, bool> = true>
int carb::cpp::popcount(T val) noexcept

Returns the number of 1 bits in the value of x.

Note

Unlike std::popcount, this function is not constexpr. This is because the compiler intrinsics used to implement this function are not constexpr until C++20, so it was decided to drop constexpr in favor of being able to use compiler intrinsics. If a constexpr implementation is required, use popcount_constexpr().

Note

(Intel/AMD CPUs) This function will check to see if the CPU supports the popcnt instruction (Intel Nehalem micro-architecture, 2008; AMD Jaguar micro-architecture, 2013), and if it is not supported, will use a fallback function that is ~85% slower than the popcnt instruction. If the compiler indicates that the target CPU has that instruction, the CPU support check can be skipped, saving about 20%. This is accomplished with command-line switches: /arch:AVX (or higher) for Visual Studio or -march=sandybridge (or several other -march options) for GCC.

Parameters

val[in] The unsigned integer value to test.

Returns

The number of 1 bits in the value of val.