ANURAG MODI
ANURAG MODI

Reputation: 33

Compute the checksum for a binary file in Python

I have a binary file(2 bytes), whose content in Hex Format are as follows :

00 00 00 DD 11 22 33 44

In binary the content looks as follows(little endian format) :

11011101 00000000 00000000 00000000 01000100 00110011 00100010 00010001 

I want to manually compute the checksum of the file and append it at the end of the file. For computing I am considering 4 bytes chunk at a time.

Then the manual steps should look as follows :

   11011101 00000000 00000000 00000000
+ 
   01000100 00110011 00100010 00010001
  --------------------------------------
=  00100001 00110011 00100010 00010001

   11011110 11001100 11011101 11101110  (1's complement)
+
   00000000 00000000 00000000 00000001  (add 1) <br/>
-----------------------------------------
=  11011110 11001100 11011101 11101111  (2's complement) = CheckSum

Please correct me, if I have computed the checksum wrongly. Code I have written to compute the checksum in the system doesn't works fine.

add = 0
with open("temp.bin", "rb") as f:
    ## Read first 4 bytes of data
    byte = f.read(4)
    while byte != "":
        add += int.from_bytes(byte, byteorder="little")
    print(b"%02X" % (~add & 0xFFFFFFFF))

Please help me with the above problem and code.

Upvotes: 1

Views: 3572

Answers (1)

blhsing
blhsing

Reputation: 106435

You aren't updating byte in your while loop, so the loop never ends.

You should keep reading from f until byte is None:

add = 0
with open("/temp/test.py", "rb") as f:
    ## Read first 4 bytes of data
    while True:
        byte = f.read(4)
        if not byte:
            break
        add += int.from_bytes(byte, byteorder='little')
    print(b'%02X' % (~add & 0xFFFFFFFF))

Upvotes: 2

Related Questions