# get power of 2 above x

## Recommended Posts

Is there a better way than this (same goes for getting the next power of other numbers?
unsigned n;
for(n=2; n<x; n*=2);

So I get:
x    -> n
419  -> 512
560  -> 1024
87   -> 128
5    -> 8
1500 -> 2048


##### Share on other sites
unsigned long next_power_of_2(unsigned long x){  unsigned long n = 1;  while(x >>= 1)    n *= 2;}

In generalized form, you'd need a function that computes the logarithm in arbitrary base b of a number x. Given that, then:
unsigned long next_power_of_b(unsigned long x, unsigned long b){  return pow(b, log(x, b)); // where log(x, b) returns logb x}

##### Share on other sites
Depends what you mean by "better". For powers of two, you can take advantage of bit shifting to do this without a loop:

http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2

I expect you could adapt this to work on powers of 4, 8, 16, etc.

Note that if this code isn't performance-critical then there's very little point in making this kind of micro-optimization, and if it is performance-critical then you shouldn't be doing anything without careful profiling. Modern processors are incredibly complex devices, and your assumptions about the relative speed of different operations might not be accurate.

## Create an account or sign in to comment

You need to be a member in order to leave a comment

## Create an account

Sign up for a new account in our community. It's easy!

Register a new account

• ### Forum Statistics

• Total Topics
628365
• Total Posts
2982273

• 10
• 9
• 13
• 24
• 11