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; + } + +}