Tech Is Hard

Credibility = Talent x Years of experience + Proven hardcore accomplishment

How to Easily and Consistently Round Up with Integer Division


I’ve encountered this in different languages for different purposes.  The first time was some assembler code that calculated how many total bytes it would take to hold an arbitrary number of bits.  The problem is it’s usually coded the way we think about the problem: divide, then if there’s a remainder, add 1 to the quotient.

A quick, easy way without any special checking, is to add the (divisor-1) to the dividend before doing the division.  In the bits to bytes example, I changed the code to do it this way

howManyBytes = (howManyBits + 7)/8

Instead of this way

howManyBytes = howManyBits/8
if (howManyBytes*8 < howManyBits)
  howManyBytes ++

You’re guaranteed to get the rounded up number without any extra work.

About these ads

2 responses to “How to Easily and Consistently Round Up with Integer Division

  1. Sjan October 3, 2012 at 2:33 pm

    It seems that unless your dev language is severely limited (as in assembler, which you mentioned) there should be some implementation of the math ceiling –

    python: howManyBytes = math.ceil( howManyBits / 8 )
    javascript: var howManyBytes = Math.ceil( howManyBits / 8 );
    php: $howManyBytes = ceil( $howManyBits / 8 );

    etc.

    • Grant Wesley Parks November 26, 2012 at 10:27 am

      Good point, but I did find this exact type of code in the Javascript I was maintaining.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: