Skip to content

Instantly share code, notes, and snippets.

@garymacindoe
Created June 18, 2015 14:44
Show Gist options
  • Save garymacindoe/f2e19c82339c103be5f3 to your computer and use it in GitHub Desktop.
Save garymacindoe/f2e19c82339c103be5f3 to your computer and use it in GitHub Desktop.
Round up to the next highest power of 2 using C++11 compile-time templates
#include <type_traits>
#include <limits>
template <typename UIntType, UIntType v, unsigned int n>
struct set_lower_bits : public std::integral_constant<UIntType, v | (v >> n) | set_lower_bits<UIntType, v | (v >> n), (n >> 1)>::value> {};
template <typename UIntType, UIntType v>
struct set_lower_bits<UIntType, v, 1> : public std::integral_constant<UIntType, v | (v >> 1)> {};
template <typename UIntType, UIntType v>
struct nextpow2 : public std::integral_constant<UIntType, set_lower_bits<UIntType, v - 1, (std::numeric_limits<UIntType>::digits >> 1)>::value + 1> {};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment