From 2bde611d3317e751c411062089d12d7b901ea4e9 Mon Sep 17 00:00:00 2001 From: Lynix Date: Mon, 16 Mar 2015 15:16:05 +0100 Subject: [PATCH] (Math) Added CountBits function Former-commit-id: 11e825a95a7bda300e46eb321f0fdb51bea93343 --- include/Nazara/Math/Algorithm.hpp | 1 + include/Nazara/Math/Algorithm.inl | 14 ++++++++++++++ 2 files changed, 15 insertions(+) diff --git a/include/Nazara/Math/Algorithm.hpp b/include/Nazara/Math/Algorithm.hpp index 92ea232bd..44b2a3f1b 100644 --- a/include/Nazara/Math/Algorithm.hpp +++ b/include/Nazara/Math/Algorithm.hpp @@ -22,6 +22,7 @@ template T NzApproach(T value, T objective, T increment); template constexpr T NzClamp(T value, T min, T max); +template T NzCountBits(T value); template constexpr T NzFromDegrees(T degrees); template constexpr T NzFromRadians(T radians); template constexpr T NzDegreeToRadian(T degrees); diff --git a/include/Nazara/Math/Algorithm.inl b/include/Nazara/Math/Algorithm.inl index 394d6a407..d935bbe07 100644 --- a/include/Nazara/Math/Algorithm.inl +++ b/include/Nazara/Math/Algorithm.inl @@ -114,6 +114,20 @@ constexpr T NzClamp(T value, T min, T max) return std::max(std::min(value, max), min); } +template +T NzCountBits(T value) +{ + // https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan + unsigned int count = 0; + while (value) + { + value &= value - 1; + count++; + } + + return count; +} + template constexpr T NzDegreeToRadian(T degrees) {