From cbb602ea83fdc757fd316cac99c3f4fba7bf0a11 Mon Sep 17 00:00:00 2001 From: Markus Birth Date: Tue, 16 Oct 2018 23:31:08 +0200 Subject: [PATCH] Move file handling into ChkSum class. --- gcksum.py | 16 +++------------- grmn/chksum.py | 11 +++++++++++ 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/gcksum.py b/gcksum.py index efad1cd..e838ed3 100644 --- a/gcksum.py +++ b/gcksum.py @@ -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())) diff --git a/grmn/chksum.py b/grmn/chksum.py index db1c468..7a01c19 100644 --- a/grmn/chksum.py +++ b/grmn/chksum.py @@ -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