CRC32

RFC 1952 - GZIP file format specification version 4.3 に載っているコードをベタ移植しただけです.

crc_table = [None] * 256

def make_crc_table():
  for n in range(256):
    c = n
    for k in range(8):
      if c & 1:
          c = 0xedb88320 ^ (c >> 1)
      else:
          c >>= 1
    crc_table[n] = c

def update_crc(crc, s):
  c = crc ^ 0xffffffff
  if crc_table[0] == None:
    make_crc_table()
  for ch in s:
    c = crc_table[(c ^ ord(ch)) & 0xff] ^ (c >> 8)
  return c ^ 0xffffffff

def crc(s):
  return update_crc(0, s)

RFC 2083 - PNG (Portable Network Graphics) Specification Version 1.0 だと 0xffffffff の挿入位置が微妙に違うのね(大差ないけど

crc_table = [None] * 256

def make_crc_table():
  for n in range(256):
    c = n
    for k in range(8):
      if c & 1:
          c = 0xedb88320 ^ (c >> 1)
      else:
          c >>= 1
    crc_table[n] = c

def update_crc(c, s):
  if crc_table[0] == None:
    make_crc_table()
  for ch in s:
    c = crc_table[(c ^ ord(ch)) & 0xff] ^ (c >> 8)
  return c

def crc(s):
  return update_crc(0xffffffff, s) ^ 0xffffffff