Skip to content

Instantly share code, notes, and snippets.

@jiixyj
Created April 27, 2012 09:47
Show Gist options
  • Save jiixyj/2507919 to your computer and use it in GitHub Desktop.
Save jiixyj/2507919 to your computer and use it in GitHub Desktop.
calculate integer binary log star on compile time
#include <climits>
namespace {
typedef unsigned long log_number_t;
// count needed bits for a number
template<log_number_t N> struct num_bits_t {
static const log_number_t value = num_bits_t<(N >> 1)>::value + 1;
};
template<> struct num_bits_t<0> {
static const log_number_t value = 0;
};
// floor(lb(n)), lb(0) = 0
template<log_number_t N> struct lb_floor_t {
static const log_number_t value = N == 0 ? 0 : num_bits_t<N>::value - 1;
};
// ceil(lb(n)), lb(0) = 0
template<log_number_t N> struct lb_ceil_t {
static const log_number_t value = N <= 1 ? 0 : lb_floor_t<N - 1>::value + 1;
};
// 0-2: 0, 3-4: 1, 5-16: 2, 17-65536: 3, 65536-: 4
template<log_number_t N> struct log_star_t {
static const log_number_t value =
N <= 2 ? 0 : log_star_t<lb_ceil_t<N>::value>::value + 1;
};
template<> struct log_star_t<0> {
static const log_number_t value = 0;
};
}
int main()
{
return log_star_t<sizeof(unsigned short) * CHAR_BIT>::value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment