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.
Like this:
Like Loading...
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.
Good point, but I did find this exact type of code in the Javascript I was maintaining.