Skip to content

Instantly share code, notes, and snippets.

@lichray
Last active December 18, 2015 06:08
Show Gist options
  • Save lichray/5737360 to your computer and use it in GitHub Desktop.
Save lichray/5737360 to your computer and use it in GitHub Desktop.
Round an integer up to the closest 2's power.
#include <limits>
#include <type_traits>
template <int bit>
struct or_shift
{
template <typename Int>
static constexpr auto apply(Int n) -> Int
{
return or_shift<bit / 2>::apply(n | (n >> bit));
}
};
template <>
struct or_shift<1>
{
template <typename Int>
static constexpr auto apply(Int n) -> Int
{
return n | (n >> 1);
}
};
template <typename Int, typename R = typename std::make_unsigned<Int>::type>
constexpr auto pow2_roundup(Int n) -> R
{
return or_shift<
std::numeric_limits<R>::digits / 2>::apply(R(n) - 1) + 1;
}
#include <iostream>
#include <iomanip>
int main()
{
using namespace std;
cout
<< "0\t" << pow2_roundup(0) << endl
<< "1\t" << pow2_roundup(1) << endl
<< "2\t" << pow2_roundup(2) << endl
<< "3\t" << pow2_roundup(3) << endl
<< "143\t" << pow2_roundup(143) << endl
<< "max\t" << pow2_roundup(numeric_limits<int>::max()) << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment