Ensure a variable is divisible by 4

geskerrett at hotmail.com geskerrett at hotmail.com
Tue Dec 5 08:02:06 EST 2006


Nick Craig-Wood wrote:
> geskerrett at hotmail.com <geskerrett at hotmail.com> wrote:
> >  I am sure this is a basic math issue, but is there a better way to
> >  ensure an int variable is divisible by 4 than by doing the following;
> >
> >  x = 111
> >  x = (x /4) * 4
>
> You should use // for future compatibility which is guaranteed to be
> an integer division whereas / isn't (see "from __future__ import
> division")
>
> Eg
>
>   (x // 4) * 4
>
> For the particular case of 4 being 2**2, you might consider
>
>   x & ~0x3
>
> which is a common idiom.
>

Thanks for the tip about integer division and I will experiment with
your other suggestion.




More information about the Python-list mailing list