unsigned 32 bit arithmetic type?

"Martin v. Löwis" martin at v.loewis.de
Wed Oct 25 13:13:38 EDT 2006


Robin Becker schrieb:
>     def add32(x, y):
>         "Calculate (x + y) modulo 2**32"
>         return ((x&0xFFFFFFFFL)+(y&0xFFFFFFFFL)) & 0xffffffffL

That's redundant; it is sufficient to write

          return (x+y) & 0xffffffff

>     def calcChecksum(data):
>         """Calculates TTF-style checksums"""
>         if len(data)&3: data = data + (4-(len(data)&3))*"\0"
>         sum = 0
>         for n in unpack(">%dl" % (len(data)>>2), data):
>             sum = add32(sum,n)
>         return sum

That's also redundant; I'd write

def calcChecksum(data):
   data += "\0\0\0\0"[:len(data)&3]
   return sum(unpack(">%dl" % (len(data)>>2), data)) & 0xffffffff

I.e. it is sufficient to truncate to 32 bits at the end, instead of
doing so after each addition.

Regards,
Martin



More information about the Python-list mailing list