News for hackers. Stuff that matters.
Re:Counting set bits in an interesting way by Const-me on Saturday April 30, 2022 @12:44PM (#31217285)
For production code as opposed to exams of job interviews, it’s usually better to use hardware implementation. All modern CPUs have instructions for that, popcnt on Intel/AMD, vcnt.8 on ARM Neon.

Many languages have standard library functions, or hardware intrinsics, to emit these instructions: std::popcount in C++/20, _popcnt32 and _popcnt64 intrinsics for Intel/AMD, __builtin_popcount in gcc/clang, BitOperations.PopCount in C#, etc.

Re:Counting set bits in an interesting way by jandrewrogers on Saturday April 30, 2022 @03:47PM (#31218690)
Compilers can often recognize idiomatic implementations of intrinsics in languages where it is not part of the standard library, doing the appropriate substitution at compile-time. This has the advantage of being highly portable to environments that either lack the intrinsics or don't recognize the idioms without conditional compilation. This typically requires a little experimentation with Godbolt or similar to identify idiomatic C expressions of intrinsics that are consistently recognized across most/all popular compilers.

That said, the reduction in diversity of target platforms, at least on the server side, combined with convergence of language extensions support in compilers has made this less useful than it used to be. I mostly just used builtins and intrinsics these days.

Re:Counting set bits in an interesting way by ChrisLomont on Saturday April 30, 2022 @03:05PM (#31218358)
>All modern CPUs have instructions for that

Not in the embedded space. Here's the architectures supported by gcc. I suspect most of them do not have popcount equivalent instructions. I've used quite a few of them and the only places I expect hardware support are on Intel and ARM. Rarely does another arch have it.

https://gcc.gnu.org/backends.html