#include <stdio.h>
#include <math.h>
#include <stdint.h>
// compute the next highest power of 2 of 64-bit v
uint64_t next_pow2(uint64_t v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
#define NB_TESTS 28
size_t tests[NB_TESTS] =
{
/* 0 */ 0,
/* 1 */ 1,
/* 2 */ 3,
/* 3 */ 10,
/* 4 */ 15,
/* 5 */ 17,
/* 6 */ 63,
/* 7 */ 100,
/* 8 */ 129,
/* 9 */ 1000,
/* 10 */ 10000,
/* 11 */ 100000,
/* 12 */ 1000000,
/* 13 */ 10000000,
/* 14 */ 100000000,
/* 15 */ 1000000000,
/* 16 */ 10000000000,
/* 17 */ 100000000000,
/* 18 */ 1000000000000,
/* 19 */ 10000000000000,
/* 20 */ 100000000000000,
/* 21 */ 1000000000000000,
/* 22 */ 10000000000000000,
/* 23 */ 100000000000000000,
/* 24 */ 9223372036854775807,
/* 25 */ 9223372036854775809UL,
/* 26 */ 9223372036854775850UL,
/* 27 */ 18446744073709551615UL,
};
int main()
{
int i;
for(i = 0; i < NB_TESTS; i++)
{
const size_t npoints = pow(2, ceil(log2(tests[i])));
printf("in=%zu out=%zu\n", tests[i], npoints);
// https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
const size_t npoints1 = next_pow2(tests[i]);
printf("in=%zu out=%zu\n", tests[i], npoints1);
}
return 0;
}