Skip to content

Instantly share code, notes, and snippets.

@colematt
Created April 3, 2024 23:07
Show Gist options
  • Save colematt/588ed655f813d845680125856253dd88 to your computer and use it in GitHub Desktop.
Save colematt/588ed655f813d845680125856253dd88 to your computer and use it in GitHub Desktop.
[Get the next power of 2 of an unsigned integer] #c
// Assuming 64-bit long
unsigned long np2(unsigned long x) {
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x |= x >> 32;
++x;
return x;
}
// Assuming x86 architecture and a compiler with __builtins
uint64_t nextpow2_64(uint64_t x) {
return x == 1 ? 1 : 1 << (64 - __builtin_clzl(x - 1));
}
// Assuming x86 architecture and a compiler with __builtins
uint32_t nextpow2_32(uint32_t x) {
return x == 1 ? 1 : 1 << (32 - __builtin_clz(x - 1));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment