Add utility header for bit manipulation functions
This commit is contained in:
parent
fe4dd717f1
commit
a93715e16e
1 changed files with 30 additions and 0 deletions
30
libs/util/include/psemek/util/bits.hpp
Normal file
30
libs/util/include/psemek/util/bits.hpp
Normal 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
Loading…
Add table
Reference in a new issue