Skip to content

Instantly share code, notes, and snippets.

@ilansmith
Last active January 6, 2022 11:39
Show Gist options
  • Save ilansmith/c6db267d6593c482e0c7958c21915986 to your computer and use it in GitHub Desktop.
Save ilansmith/c6db267d6593c482e0c7958c21915986 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#if defined(DEBUG)
#define PRINT(_fmt_, ...) printf(_fmt_, __VA_ARGS__);
#else
#define PRINT(_fmt_, ...)
#endif
/* works in the range: [0x1, 0x7FFF FFFF FFFF FFFF] */
static size_t upper_power_of_two(size_t v)
{
int i;
PRINT("v: 0x%.16lx\n", v);
v--;
PRINT("v--: 0x%.16lx\n", v);
for (i = 0; i < 6; i++) {
v |= v >> (1 << i);
PRINT("v |= v >> (1 << %d): 0x%.16lx\n", i, v);
}
v++;
PRINT("v++: 0x%.16lx\n", v);
return v;
}
int main(int argc, char **argv)
{
size_t val = 0x7000000000000001;
printf("upper_power_of_two(%lu) = %lu\n", val,
upper_power_of_two(val));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment