Ensure a variable is divisible by 4

Grant Edwards grante at visi.com
Mon Dec 4 13:57:05 EST 2006


On 2006-12-04, 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

if x & 3:
  print "not divisible by 4"

x &= ~3

print "it is now: x = %d"

If you want to round to nearest power of 4 rather than truncate:

x = (x+2) & ~3

-- 
Grant Edwards                   grante             Yow!  An INK-LING? Sure --
                                  at               TAKE one!! Did you BUY any
                               visi.com            COMMUNIST UNIFORMS??



More information about the Python-list mailing list