From a93715e16e353b0107530c3e697f5a1a6ff4562e Mon Sep 17 00:00:00 2001 From: lisyarus Date: Tue, 6 Jul 2021 22:00:57 +0300 Subject: [PATCH] Add utility header for bit manipulation functions --- libs/util/include/psemek/util/bits.hpp | 30 ++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 libs/util/include/psemek/util/bits.hpp diff --git a/libs/util/include/psemek/util/bits.hpp b/libs/util/include/psemek/util/bits.hpp new file mode 100644 index 00000000..9f17bf9d --- /dev/null +++ b/libs/util/include/psemek/util/bits.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include + +namespace psemek::util +{ + + // round up to power of 2 + template + T round_pow2(T x) + { + static_assert(std::is_integral_v); + static_assert(std::is_unsigned_v); + + x--; + x |= x >> 1; + x |= x >> 2; + x |= x >> 4; + if constexpr (sizeof(T) >= 2) + x |= x >> 8; + if constexpr (sizeof(T) >= 4) + x |= x >> 16; + if constexpr (sizeof(T) >= 8) + x |= x >> 32; + x++; + + return x; + } + +}