Add utility header for bit manipulation functions

This commit is contained in:
Nikita Lisitsa 2021-07-06 22:00:57 +03:00
parent fe4dd717f1
commit a93715e16e

View file

@ -0,0 +1,30 @@
#pragma once
#include <type_traits>
namespace psemek::util
{
// round up to power of 2
template <typename T>
T round_pow2(T x)
{
static_assert(std::is_integral_v<T>);
static_assert(std::is_unsigned_v<T>);
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;
}
}