Jump to content
  • Advertisement
Sign in to follow this  
Sync Views

get power of 2 above x

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
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
}

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!