get power of 2 above x

Started by
1 comment, last by dwahler 15 years, 11 months ago
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
Advertisement
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}
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.

This topic is closed to new replies.

Advertisement