Checksum Calculation

The CheckSum32 function I propose calculates the 32 bits checksum of a string, using a currency variable to avoid overflow errors.

Function CheckSum32(A$) As Long
'Calculates the 32bits checksum of a string
Const MAXULONG = 4294967295# 'Max unsigned long integer
Const MAXLONG = 2147483647 'Max signed long integer
Dim Sum As Currency 'Currency variable type to avoid overflow
Dim i As Integer 'Source string character counter
Dim j As Integer 'Checksum byte counter (byte # = 0..3)
    j = 0
    For i = 1 To Len(A$)
        'Add byte at relevant position in sum
        Sum = Sum + (Asc(Mid$(A$, i, 1)) * 256 ^ j)
        'remove 33d bit if set
        If Sum > MAXULONG Then Sum = Sum - (MAXULONG + 1)
            'skip to next byte in sum
        If j < 3 Then
            j = j + 1
            Else
              j = 0
        End If
    Next
    'Conversion for signed long integer result
    If Sum > MAXLONG Then Sum = Sum - (MAXULONG + 1)
    CheckSum32 = Sum
End Function

 

Tip Submitted By: Marc Lajus

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s