• What is your GameDev Story?

Archived

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.

Recommended Posts

How would I round to the nearest 32? Can you give the code in C++? Thanks in advance

Share on other sites
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 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 on other sites
Assuming the variable i is an unsigned 32 bit integer:

(i + 16) & (0xffffffff ^ 31)

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.

Thanks!

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 on other sites
Wouldn''t:
i = (i + 16) & ~31;

do it?

Share on other sites
quote:
Original post by DigitalDelusion
Wouldn''t:
i = (i + 16) & ~31;

do it?

Yep.

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

• What is your GameDev Story?

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

• 15
• 9
• 11
• 9
• 9
• Forum Statistics

• Total Topics
634136
• Total Posts
3015756
×