How to Easily and Consistently Round Up with Integer Division
October 2, 2012
Posted by on
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)
You’re guaranteed to get the rounded up number without any extra work.