tags:

views:

821

answers:

4

I want calculate crc of file, and get output like [E45A12AC] I don't want md5 or other.

#!/usr/bin/env python 
import os, sys
import zlib

def crc(fileName):
  fd = open(fileName,"rb")
  content = fd.readlines()
  fd.close()
  for eachLine in content:
   zlib.crc32(eachLine)

for eachFile in sys.argv[1:]:
 crc(eachFile)

calculates for each line crc, but its output <-1767935985> per line is not what i want. How to get output like: [E45A12AC] ?

is it posible with zlib.crc32 do something like:

import hashlib
m = hashlib.md5()
for line in open('data.txt', 'rb'):
    m.update(line)
print m.hexdigest()
A: 
bhups
Thanks for syntax.I get LTc3NzI0ODI2, but i want E45A12AC (8 digits). Tried base32, base16.
The OP wants to see the CRC32 as hex, not as base64-encoded.
ΤΖΩΤΖΙΟΥ
+2  A: 

To show any integer's lowest 32 bits as 8 hexadecimal digits, without sign, you can "mask" the value by bit-and'ing it with a mask made of 32 bits all at value 1, then apply formatting. I.e.:

>>> x = -1767935985
>>> format(x & 0xFFFFFFFF, '08x')
'969f700f'

It's quite irrelevant whether the integer you are thus formatting comes from zlib.crc32 or any other computation whatsoever.

Alex Martelli
+1  A: 

solution:

import os, sys
import zlib

def crc(fileName, excludeLine="", includeLine=""):
  try:
        fd = open(fileName,"rb")
  except IOError:
        print "Unable to open the file in readmode:", filename
        return
  eachLine = fd.readline()
  prev = None
  while eachLine:
      if excludeLine and eachLine.startswith(excludeLine):
            continue   
      if not prev:
        prev = zlib.crc32(eachLine)
      else:
        prev = zlib.crc32(eachLine, prev)
      eachLine = fd.readline()
  fd.close()    
  return format(prev & 0xFFFFFFFF, '08x') #returns 8 digits crc

for eachFile in sys.argv[1:]:
    print crc(eachFile)

don't realy know for what is (excludeLine="", includeLine="")...

A: 

A little more compact and optimized code

def crc(fileName):
prev = 0
for eachLine in open(fileName,"rb"):
    prev = zlib.crc32(eachLine, prev)
return "%X"%(prev & 0xFFFFFFFF)

PS2: Old PS is deprecated - therefore deleted -, because of the suggestion in the comment. Thank you. I don't get, how I missed this, but it was really good.

kobor42
If you set `prev` to 0 instead then you don't need to worry about an exception.
Ignacio Vazquez-Abrams