From c6bd01b2f2c33d5e752cd207a5b779b818a80aa0 Mon Sep 17 00:00:00 2001 From: Jonathan G Rennison Date: Sun, 5 Dec 2021 17:40:42 +0000 Subject: [PATCH] Add an IsOddParity bitmath function --- src/core/bitmath_func.hpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/core/bitmath_func.hpp b/src/core/bitmath_func.hpp index 18684dc637..c4cc4d6153 100644 --- a/src/core/bitmath_func.hpp +++ b/src/core/bitmath_func.hpp @@ -317,6 +317,30 @@ static inline uint CountBits(T value) #endif } +/** + * Return whether the input has odd parity (odd number of bits set). + * + * @param value the value to return the parity of. + * @return true if the parity is odd. + */ +template +static inline bool IsOddParity(T value) +{ + static_assert(sizeof(T) <= sizeof(unsigned long long)); +#ifdef WITH_BITMATH_BUILTINS + typename std::make_unsigned::type unsigned_value = value; + if (sizeof(T) <= sizeof(unsigned int)) { + return __builtin_parity(unsigned_value); + } else if (sizeof(T) == sizeof(unsigned long)) { + return __builtin_parityl(unsigned_value); + } else { + return __builtin_parityll(unsigned_value); + } +#else + return CountBits(value) & 1; +#endif +} + /** * Test whether \a value has exactly 1 bit set *