|No such thing as a small change|
How to do popcount (aka Hamming weight) in Perlby eyepopslikeamosquito (Bishop)
|on Sep 24, 2017 at 10:23 UTC||Need Help??|
eyepopslikeamosquito has asked for the wisdom of the Perl Monks concerning the following question:
I started with the basic popcount1 below, scraped with little thought from the Hamming_weight wikipedia page.
I'd like to improve that, hence this node.
Running the above program on my machine produced:
Update: Added some C/C++ information from Hamming weight (wikipedia).
Some C compilers provide intrinsic functions that provide bit counting facilities. For example, GCC (since version 3.4 in April 2004) includes a builtin function __builtin_popcount that will use a processor instruction if available or an efficient library implementation otherwise. LLVM-GCC has included this function since version 1.5 in June 2005.
In C++ STL, the bit-array data structure bitset has a count() method that counts the number of bits that are set. In C++20, a new header <bit> was added, containing functions std::popcount and std::has_single_bit, taking arguments of unsigned integer types.
I've used this for code that builds with both GCC and MSVC:
Updated: Added more references (thanks oiskuu)