• entries
503
1888
• views
335749

# Sweet Snippet

119 views

After browsing the net a bit, I found the code that can be used for rounding a number up to the next power of two. While I am banking on D3DXCreateTexture to do it for me, it can be helpful in other situations, so I thought I would post it.

I converted it into a simple routine:

/** * Function for rounding a number up to the next power of two. * n - an integer number to be rounded * returns - n rounded up to the next power of two*/int roundUpToPow2(int n){	int e;	frexp((float)n-1,&e);	return (int)pow(2,e);}

it requires the inclusion of math.h

and the basic idea of how it works, is you use frexp to get the exponent of the incomming number, then you do 2 to the e'th (exponent) and it gives you back the proper pow2 number, quite handy =)

you put in 255, it gives you 256
you put in 257, it gives you 512
you put in 256, it gives you 256

Here's how I've been doing it. A really, really simple version. :)

int NextPowerOfTwo(int i)
{
int iReturn = 1;

while(iReturn < i)
{
iReturn <<= 1;
}

return iReturn;
}



Edit:
Just ran some speed tests, (so that I'd know if I'd need to steal your version) and it looks like the version I've been using is just a touch faster. Over ten million iterations, it's about half a second faster. Not worth much, just thought I'd share.

Oh, I also wanted to mention something in regards to the question asked in comments for your last post. If you're interested at all in targeting OSX or Linux, I might be able to help you with that. I've rewritten my 2d/3d OpenGL based engine half a dozen times, so I think I'd be able to port your D3D engine over. Lemme know what you think.

Passing in a negative number won't always work. Try putting in -255, the output will be 512. I suppose you probably wouldn't be passing negative numbers to the function though...

You could solve that by making n an unsigned int, but then you'll get wonky results if you pass 0 to the function.

There's also a couple of ideas here.

pow(int, int) works with doubles - you only need an integer and it's always pow2 so you could use operator <<. I wouldn't let it take signed integers either, it makes it ambiguous and invites trouble. Should -257 go to -256 (more positive), -512 (higher magnitude), 1 (next actual 'proper' power of 2), or even 0?

Also, i have a feeling you're using this for sizing textures, and a -1 x -1 texture wouldn't make much sense :)

I've always found this way to be fun:

unsigned int NextPowerOfTwo(unsigned int v)
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}



That works for any 32-bit (unsigned) integer, though anything over 2^31 will round up to 0.

## Create an account

Register a new account

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.