Jump to content
  • Advertisement

Archived

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

CloudNine

Rounding to the nearest 32

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

Advertisement
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
1.2=1.0
1.6=2.0

and rounding to the nearest 10
12=10
16=20


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;
else
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 GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!