From c28ab4461fd7868cff200283cc4cf6aded0f331f Mon Sep 17 00:00:00 2001 From: David Robillard Date: Sun, 12 Aug 2018 22:27:55 +0200 Subject: Add pop count operations --- chilbert/BigBitVec.hpp | 10 ++++++++++ chilbert/FixBitVec.hpp | 3 +++ chilbert/Operations.hpp | 18 ++++++++++++++++++ 3 files changed, 31 insertions(+) (limited to 'chilbert') diff --git a/chilbert/BigBitVec.hpp b/chilbert/BigBitVec.hpp index 83b8a5b..8f8dc6d 100644 --- a/chilbert/BigBitVec.hpp +++ b/chilbert/BigBitVec.hpp @@ -422,6 +422,16 @@ public: return 0; } + /// Return the number of set bits + size_t count() const + { + size_t c = 0; + for (size_t i = 0; i < m_iRacks; ++i) { + c += static_cast(pop_count(m_pcRacks[i])); + } + return c; + } + /// Flip all bits (one's complement) CBigBitVec& flip() { diff --git a/chilbert/FixBitVec.hpp b/chilbert/FixBitVec.hpp index e47b868..bba25d9 100644 --- a/chilbert/FixBitVec.hpp +++ b/chilbert/FixBitVec.hpp @@ -224,6 +224,9 @@ public: return static_cast(chilbert::ffs(m_rack)); } + /// Return the number of set bits + size_t count() const { return static_cast(pop_count(m_rack)); } + /// Flip all bits (one's complement) CFixBitVec& flip() { diff --git a/chilbert/Operations.hpp b/chilbert/Operations.hpp index b2e4344..5781e6c 100644 --- a/chilbert/Operations.hpp +++ b/chilbert/Operations.hpp @@ -88,6 +88,24 @@ setBit(T& field, const BitsetIndex index, const bool value) field.set(index, value); } +/// Return 1 + the index of the least significant 1-bit of `field`, or zero +template +int pop_count(const T& field); + +template <> +int +pop_count(const unsigned long& field) +{ + return __builtin_popcountl(field); +} + +template <> +int +pop_count(const unsigned long long& field) +{ + return __builtin_popcountll(field); +} + /// Return 1 + the index of the least significant 1-bit of `field`, or zero template int ffs(const T field); -- cgit v1.2.1