Python checksum Calculation
The Checksum is frequently used. Here, we simply list a code snippet for the sum calculated by byte. In fact, this sum calculation translates bytes into unsigned integers and signed integers, and the results are the same.
Use python for verification and keep in mind to perform truncation. This is just a sample code, right as a flag, directly on the code
'''Created on September 4, 2014 @ author: lenovo ''' import random ''' the actual verification result must be the same if it is interpreted as an unsigned integer or a signed integer. Because it is stored Based on the CAPTCHA complement method, bitwise addition is used for calculation, and the carry is carried. It is only the final result. If it is a signed integer, the highest bit will be interpreted as the symbol bit '''def char_checksum (data, byteorder = 'little '): ''' char_checksum calculates the checksum in bytes. Each byte is translated into a signed integer @ param data: byte string @ param byteorder: Large/small-end ''' length = len (data) checksum = 0 for I in range (0, length): x = int. from_bytes (data [I: I + 1], byteorder, signed = True) if x> 0 and checksum> 0: checksum + = x if checksum> 0x7F: # overflow checksum = (checksum & 0x7F)-0x80 # The complement code is the corresponding negative value elif x <0 and checksum <0: checksum + = x if checksum <-0x80: # overflow checksum & = 0x7F else: checksum + = x # Positive and Negative addition, no overflow # Print (checksum) return checksum def uchar_checksum (data, byteorder = 'little '): ''' char_checksum calculates the checksum in bytes. Each byte is translated into an unsigned integer @ param data: byte string @ param byteorder: Large/small-end ''' length = len (data) checksum = 0 for I in range (0, length): checksum + = int. from_bytes (data [I: I + 1], byteorder, signed = False) checksum & = 0xFF # force truncation return checksum
Briefly describe the above script. If it is calculated as an unsigned integer, the algorithm is much simpler and can actually be reduced to a code. If it is calculated as a signed integer, the algorithm needs to be complex and handle various overflow and underflow situations. As pointed out at the beginning of the article, no matter which method is used, the final binary representation is the same. Therefore, you can use unsigned integers to calculate the checksum, which is simple and fast.
The following is an example of verification,
data1=bytes(b'\x01\x7F\xFF') data2=bytes([random.randrange(0,256) for i in range(0, 10000)]) assert(uchar_checksum(data1) == 127) assert(char_checksum(data1) == 127) assert((uchar_checksum(data2)&0xFF) == (char_checksum(data2)&0xFF)) print('OK')
The above algorithm can easily be extended to two or four bytes of checksum calculation.
Over