Skip to content

Instantly share code, notes, and snippets.

@jmbr
Created July 11, 2012 12:19
Show Gist options
  • Save jmbr/3090021 to your computer and use it in GitHub Desktop.
Save jmbr/3090021 to your computer and use it in GitHub Desktop.
Next power of two
#include <cmath>
inline unsigned next_power_of_two(unsigned x) {
return unsigned(exp2f(ceilf(log2f(float(x)))));
}
@607011
Copy link

607011 commented Nov 16, 2012

// same without floating point operations
unsigned int next_power_of_two(unsigned int v) {
--v;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
++v;
return v;
}

@jmbr
Copy link
Author

jmbr commented Jan 20, 2013

Thanks, ola-ct. I too was aware of that solution, which can be found in Chapter 3 of the book Hacker's Delight.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment