Python vs. Perl, which is better to learn?

Andrew Dalke dalke at dalkescientific.com
Thu May 9 14:12:37 EDT 2002


James J. Besemer
>Funniest mistake I ever ran into was at one point I was supposed to come
>up with a simple encryption algorithm.  Somehow I discovered "TEA" the
>Tiny Encryption Algorithm, which sounded ideal:
>
>    http://vader.brad.ac.uk/tea/tea.shtml
>
...
>Of
>course, the algorithm relied on a Ring of 32 bit integers and Python
>complains about overflow.  I was not aware of a way to shut off the
>overflow checks (still don't) and exceptions wouldn't help as they give
>you control after the bad code has been taken out of circulation.
  ...
> I pondered for a while adding the necessary masking operations but
> decided it was not sane.

Why isn't it sane?  I think suppressing overflow checks isn't the right
way to think about it but masking is.  Here's the ANSI C version from
that page, for encoding

void encipher(const unsigned long *const v,unsigned long *const w,
   const unsigned long * const k)
{
   register unsigned long       y=v[0],z=v[1],sum=0,delta=0x9E3779B9,
    a=k[0],b=k[1],c=k[2],d=k[3],n=32;

   while(n-->0)
      {
      sum += delta;
      y += (z << 4)+a ^ z+sum ^ (z >> 5)+b;
      z += (y << 4)+c ^ y+sum ^ (y >> 5)+d;
      }

   w[0]=y; w[1]=z;
}


Here's the (completely untested and probably incorrect Python but
close enough for the gist)

def encipher(v, k):
  low32bits = 2L**32-1
  high32bits = low32bits << 32
  y = v & low32bits
  z = v & high32bits
  sum = 0L
  delta = 0x9E3779B9
  a = k & low32bits
  b = k & high32bits
  c = (k>>32) & low32bits
  d = (k>>32) & high32bits

  for i in range(32):
      sum += delta
      y = (y + (z << 4)+a ^ z+sum ^ (z >> 5)+b) & low32bits
      z = (z + (y << 4)+c ^ y+sum ^ (y >> 5)+d) & low32bits

  return w

Seems reasonable enough to me, and not very insane.  This
works, btw, on Python's long integers, which is more sane
(IMO) than C's "unsigned long *" for passing in a 64 or 128
bit value.

                    Andrew






More information about the Python-list mailing list