From 2bbabb4daf17555708b607e2a22ca3badbf30885 Mon Sep 17 00:00:00 2001 From: Robin Getz Date: Tue, 15 Sep 2026 00:25:34 -0400 Subject: [PATCH] popcount : Increase portability of fallback popcount implementation The previous implementation shifted a signed 32-bit value by up to 31 bits, which is implementation-defined behavior. It also had a fixed 32-bit limit and different semantics from the compiler built-ins. Use unsigned integer semantics and Brian Kernighan's method for the portable popcount implementation. This avoids implementation-defined signed right shifts and counts all bits in the unsigned integer type, matching the semantics of the compiler built-ins and C++20 std::popcount, and should have a minor speed improvement for random samples. Found by cppcheck (shiftTooManyBitsSigned) Signed-off-by: Robin Getz --- sdrbase/util/popcount.h | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/sdrbase/util/popcount.h b/sdrbase/util/popcount.h index 974a5b0b1..79cc62838 100644 --- a/sdrbase/util/popcount.h +++ b/sdrbase/util/popcount.h @@ -31,11 +31,17 @@ #include #define popcount __popcnt #else -static int popcount(int in) +// https://en.cppreference.com/cpp/numeric/popcount +// std::popcount requires an unsigned integer type. +// +// Brian Kernighan's method: +// https://graphics.stanford.edu/~seander/bithacks.html +static int popcount(unsigned int in) { - int cnt = 0; - for(int i = 0; i < 32; i++) - cnt += (in >> i) & 1; + for (int cnt = 0; in; cnt++) + { + in &= in - 1; // clear the least significant bit set + } return cnt; } #endif