Public Group

# get power of 2 above x

This topic is 3876 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## 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.

1. 1
2. 2
Rutin
20
3. 3
khawk
16
4. 4
A4L
14
5. 5

• 12
• 16
• 26
• 10
• 11
• ### Forum Statistics

• Total Topics
633756
• Total Posts
3013709
×