[Tutor] rounding up to the nearest multiple of 8

Albert-Jan Roskam fomcl at yahoo.com
Thu Oct 4 21:47:18 CEST 2012


Hi,
 
The function below works, but it's such a kludge! Is there a way to make this more elegant?
As said in the docstring, I want to round up a given integer to the nearest multiple of 8. I was thinking
of something like math.ceil.
 
def _getPadding(charlen):
    """ Helper function to replace null bytes ('\x00') at the end of
    string values. Rounds up <charlen> to the nearest multiple of 8.
    Every string value is 8 bytes or a multiple thereof. For example, a
    5-character string needs a padding of 3 spaces to prevent the
    null bytes
    >>> dict([(charlen, _getPadding(charlen)) for charlen in range(1, 40, 7)])
    {1: 8, 36: 40, 8: 8, 15: 16, 22: 24, 29: 32}
    >>> s = "I love Python"
    >>> s.ljust(_getPadding(len(s)))
    'I love Python   '
    """
    i = 0
    while True:
        i += 1
        if (i * 8) > charlen:
            return (i * 8) % charlen + charlen if charlen > 1 else 8
if __name__ == "__main__":
    import doctest
    doctest.testmod()

Thanks!

Regards,
Albert-Jan


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 


More information about the Tutor mailing list