Browse Source

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 <rgetz503@gmail.com>
chirpmodem-v8.0.0
Robin Getz 2 months ago
parent
commit
2bbabb4daf
No known key found for this signature in database
GPG Key ID: 51C7231FFED0E060
  1. 14
      sdrbase/util/popcount.h

14
sdrbase/util/popcount.h

@ -31,11 +31,17 @@ @@ -31,11 +31,17 @@
#include <intrin.h>
#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

Loading…
Cancel
Save