Ensure a variable is divisible by 4

Nick Craig-Wood nick at craig-wood.com
Mon Dec 4 13:30:04 EST 2006


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.

If you want to round to the next largest 4 then add 3 first, eg

  for x in range(0,12):
     (x + 3) & ~0x3

Which prints 0,4,4,4,4,8,8,8,8,12...

You could also consider the funky

  x>>2<<2

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list