Advertisement Jump to content


This topic is now archived and is closed to further replies.


Rounding to the nearest 32

This topic is 5893 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

Figure out this and you will know how to solve your problem:

You already know how to round to the nearest 1, now how do you round to the nearest 10:

For example rounding to the nearest 1

and rounding to the nearest 10

Share this post

Link to post
Share on other sites
Set the bottom five bits to zero.

Oh, nearest?

Examine the bottom five bits, and either subtract them or add 32 - bottom five bits, I guess.

[edited by - DrPizza on December 4, 2002 12:24:06 PM]

Share this post

Link to post
Share on other sites
x = n % 32;
if( x )
if( x > 16 )
n += 32 - x;
n -= x;

It''s not super-fast or anything, but it''s clear what it does.

Share this post

Link to post
Share on other sites
Well, a (very) QUICK way to round down to the nearest 32 is:

int i = 567; // any #

i >>= 5;
i <<= 5;

cout << i;

result is 544.

I''m not so sure about rounding up, i''ll think on it a little more

Share this post

Link to post
Share on other sites
This gives rise to a quick and easy shortcut for whenever you wish to round a number to a power of 2. For the next highest, given i to be the original number and n to be the power of 2 you wish to round to, then this does the trick:
i = (i + (n-1)) & ~(n-1);

If you wish to round to the nearest power of 2, it would look like this:
i = (i + (n/2)) & ~(n-1);

Also, a quick note about the shift method. You want to combine those two statements into a single one like this:
i = (i >> 5) << 5;
What happens when you have the two assignments is that the compiler moves i into a register, does the shift, and then moves it back into i. However, when we then go to do the second shift, it moves it back into the register again. This is just a useless instruction. If we combine it into a single statement, it only performs two move instructions as opposed to the four.

All things said and done, it comes down to two arithmetic shifts versus an add and an and. The latter is much faster. But really only by a few cycles. We''re working in the days of P4s, not 486s

Sorry for being nitpicky, it''s just one of those days

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!