[EMAIL PROTECTED] <[EMAIL PROTECTED]> 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 <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to