

We read every byte of the file and convert it into hash using the hexidigest() method.

In this example, we have iterated through the file using a loop. Hash = hashlib.sha256(bytes).hexdigest()

Sums the ASCII character values mod256 and returns Rem = -temp # two's complement, easier wayĪ more Pythonic (and faster) implementation would be a one-liner like this which makes use of the built-in sum() function: def calc_checksum(s): # rem = (temp ^ 0xFF) + 1 # two's complement, hard way (one's complement + 1) Here's a working version of your function: def calc_checksum(string): An really easy way to do that is just convert the lower byte of the value to uppercase hexadecimal using the % string interpolation operator. This means that just taking the last two characters of the uppercased result would be incorrect. With the -24 two's complement in this case it produces -0x18, not 0xffe8 or something similar. There's at least a couple of ways to do that correctly.Ī second problem is way the hex() function handles negative numbers is not what you'd might expect. One problem is that it doesn't calculate the two's complement correctly on the line with the comment #inverse in your code.
PYTHON CHECKSUM CODE
How do you know that's the correct answer?Īfter seeing Mark Ransom's comment that the C# code does indeed return E8, I spent some time debugging your Python code and found out why it doesn't produce the same result.
PYTHON CHECKSUM MANUAL
Given the description in the manual and doing the calculations by hand, I don't see how their answer could be 74. It outputs is E8 for the message shown which is different from both your and the C# code. Their Code C#: private string checksum(string s)įWIW, here's a literal translation of the C# code into Python: def calc_checksum(s): Sums the ASCII character values mod256 and takes

My Code (Python) def calc_checksum (string):Ĭalculates checksum for sending commands to the ELKM1. As test data I have been using '00300005000' which should return a checksum of 74 The vendor has a tool which will calculate the correct checksum. When all the characters are added to the Checksum, the value should equal 0." Permissible characters are ASCII 0-9 and upper case A-F. From their manual: "This is the hexadecimal two‟s complement of the modulo-256 sum of the ASCII values of all characters in the message excluding the checksum itself and the CR-LF terminator at the end of the message. I put together the python code below but it doesn't appear to be returning the correct value.Īccording to the documentation the checksum of the message needs to be the sum of the ASCII values of the message in mod256 then taken as 2s complement. I have sample code in C# below which apparently correctly calculates the checksum needed when sending messages to this system. I am working on an interface in Python to a home automation system (ElkM1).
