Move file handling into ChkSum class.

This commit is contained in:
Markus Birth 2018-10-16 23:31:08 +02:00
parent 43dfdbe8b2
commit cbb602ea83
Signed by: mbirth
GPG Key ID: A9928D7A098C3A9A
2 changed files with 14 additions and 13 deletions

View File

@ -5,21 +5,11 @@ from grmn import ChkSum
import sys
FILE = sys.argv[1]
BLOCKSIZE = 4 * 1024
print("Reading {} ".format(FILE), end="")
csum = ChkSum()
with open(FILE, "rb") as f:
while True:
block = f.read(BLOCKSIZE)
csum.add(block)
print(".", end="", flush=True)
if len(block) < BLOCKSIZE:
print(" done.")
break
f.close()
print("Reading {} ...".format(FILE), end="", flush=True)
csum.add_from_file(FILE, print_progress=True)
print(" done.")
print("Sum of all bytes: {:02x}".format(csum.get_sum()))
print("Last byte: {:02x}".format(csum.get_last_byte()))

View File

@ -15,6 +15,17 @@ class ChkSum:
self.last_byte = data[-1]
self.chksum += self.last_byte
self.chksum &= 0xff
def add_from_file(self, filename: str, print_progress: bool = False, blocksize: int=16384):
with open(filename, "rb") as f:
while True:
block = f.read(blocksize)
self.add(block)
if print_progress:
print(".", end="", flush=True)
if len(block) < blocksize:
break
f.close()
def get(self):
remainder = ( 0x100 - self.chksum ) & 0xff